Adjust or alter relationship attributes in py2neo

How can I update a relationship property in py2neo or cypher after it has been initially set? In my inventory tracking system, when an item is checked out, the "status" property in the relationship is set to "True". However, I'd like to change this property to "False" once the item is returned or checked back in. This will help me keep track of items and prevent them from being checked out multiple times.

Below is the code I am currently using to create the relationship for a checkout transaction:

    def check_out(self, barcode):
        emp = self
        item = barcode
        id = str(uuid.uuid4())
        timestamp = int(datetime.now().strftime("%s"))
        date = datetime.now().strftime("%F")
        status=True
        rel = Relationship(emp, "CHECKED_OUT", item, id=id, timestamp=timestamp, date=date, status=status)
        if not(graph.create_unique(rel)):
            return True
        else:
            return False

I have gone through the py2neo API documentation but haven't found a solution. If modifying the relationship is not the right approach, do you have any suggestions for a better method?

Answer №1

If you need to accomplish a similar task, this code snippet might be helpful:

def update_status(self, barcode):
    item = barcode

    # access the relationship
    for rel in graph.match(start_node=self, rel_type="UPDATE_STATUS", end_node=item):
        # modify property value
        rel.properties["status"] = True
        rel.push()

Take a look at match():

and properties: http://py2neo.org/2.0/docs/database-api.html#relationship-properties

Answer №2

I am truly grateful for your assistance. While your solution did work, it updated all relationships between the item and the person which was not my intention. I made some adjustments to your code to ensure that only the targeted relationship is updated. Once again, thank you for your help. Below is the updated version of the code:

    def check_in(self, barcode, id):
        item = barcode

        #retrieve the specific relationship
        for rel in graph.match(start_node=self, rel_type="CHECKED_OUT", end_node=item):
            if rel["id"] == id:
                #update property
                rel.properties["status"] = False
                rel.push()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently zipping lists of varying sizes

I currently have 3 different lists. >>> list1 = [1,2,3,4,5] >>> list2 = ['a','b','c','d'] >>> list3 = ['x','y','z'] Is there a Python function that can zip t ...

Combining two CSV files in Python and annotating any records that do not match in both the master and the additional

As a beginner in Python, I apologize if my question is not on point. I have two CSV files that are structured similarly and I need to match them. File 1 sa_name ABC DEF ACE ABCD BCD And File 2 rs_name ABCD CDE DEFG ABCDE ABE I want ...

Is there a way to extract and send all console data using Python through email?

I've been working on a code that schedules jobs, takes screenshots on the chromedriver, and emails them. I'm currently exploring ways to capture the console output to a file for later emailing. Below is a snippet of the code for the scheduler and ...

How to fetch clear text comments from a post using the Imgur API in Python 2.7?

client = ImgurClient(client_id, client_secret, access_token, refresh_token) for item in client.gallery_item_comments("c1SN8", sort='best'): print item I have this code snippet above. My goal is to retrieve a list of comment ids from the func ...

What is the process for creating a Python object with a non-contiguous buffer that is retrieved using `PyObject_GetBuffer`?

The Python C API has a handy function called PyBuffer_IsContiguous that can be used to check if the buffer returned is contiguous. Is there a way to create an object that will cause this function to return false? Several attempts have been made (all test ...

Change time into a string format including milliseconds

Is there a way in Python to convert the current time, including milliseconds, from the datetime.now() function into a string format? 2014-08-22 19:23:40.630000 I considered using time.strftime() but it does not seem to support milliseconds. Are there any ...

Is it possible to use the Weka plugin for Fiji in Python?

After utilizing the Weka plugin within Fiji to generate a classifier, I received both an arff file and a .model file (classifier). I am curious if it's possible to integrate this into Python for SVM application. Here is a snapshot of how I am currentl ...

There appears to be a shift in the directory when executing a Python script in Vscode

My current challenge seems to stem from a vscode-related issue. When I use the open() function in my Python script, I consistently encounter a directory error no matter the specified task. The file that should be interacted with is located in the same fold ...

What is the best method to override a class attribute that is two levels deep?

When it comes to overriding and inheritance, I've noticed that things are not working as expected in my code. Let me break down the scenario for you: I have three classes - Card, Treasure, and Copper. Copper inherits from Treasure, and Treasure inheri ...

peewee: What happens to an invalid field when I call create()?

When using Peewee, I noticed that if an instance is created with the create() method and an invalid field name is provided, no error is produced. What happens to the invalid field? Does it simply remain as it is? from peewee import * from playhouse.shortc ...

TableView fails to reflect changes made in TableModel following sorting operation

Utilizing the PyQt5 MV programming pattern, the goal is to showcase a dataframe and execute basic sorting and filtering operations on it. Although displaying the dataframe was successful, I encountered a challenge with the sorting functionality. Despite v ...

Django is experiencing a CSRF verification failure because the token is not persisting between the GET and POST requests

After reviewing several older CSRF-related inquiries, I realized that the solutions provided are outdated and not applicable anymore due to changes in handling with render() or other built-in methods. So, here's my query: I have a form template rende ...

Python code for arranging the output in numerical sequence

My program reads the last line of multiple files simultaneously and displays the output as a list of tuples. from os import listdir from os.path import isfile, join import subprocess path = "/home/abc/xyz/200/coord_b/" filename_last_l ...

Steps to start a Chromium program with the help of Chromedriver

Can I adapt this python code to work with Robot Framework? from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.action_chains import ActionChains chrome_options = Options() chrome_options.bin ...

What factors should be considered when deciding whether to create an entity in Django using Tastypie, based on data from another entity?

In my Event class, I have defined the number of participants and the participant limit. Additionally, there is a Ticket class which represents registration for the Event. I need to ensure that tickets for an event are not created if the event has reached ...

Graph the results of a set of linear inequalities

Two arrays of numbers ranging from -1 to 1 have been generated: a = 2*np.random.sample(100)-1 and b = 2*np.random.sample(100)-1. These arrays represent a system of linear inequalities defined by: a[i]*x + b[i]*y <= 1 for i = 0,1,..., 99 The solution ...

Finish the n-Digit Multiplicand

I've been working on a problem, but the time complexity of my code is very high. Is there a way to reduce it? Below is the question along with my current code implementation. A number is considered a complete 'n' digit factor if it can divid ...

"Troubleshooting: Issues with Silent Failures in ParallelPyEnvironment Using Tf-A

I have created a specialized environment to experiment with reinforcement learning using PPO and tf-agents. While everything runs smoothly when I wrap my environment (which inherits from py_environment.PyEnvironment) in a TfPyEnvironment, it fails when att ...

Using an `if else` statement to verify various conditions with only one input of text

I am experimenting with a modified version of the classic 3-Cup Monte Program. Students are using Brython in CodeHS Ide to create a game where they draw "cups" and randomly place a white ball under one of them. The drawing part is working perfectly fine. H ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...