Django – Save override to update fields issue

Issue

Having trouble with figuring out a way to update fields of a table through the save method override and have the updated value factor in values from previous saved objects that share the same primary key.

Let me explain:

I have two tables, table A and table B. Table A has a field that is the foreign key PK of table B. Multiple objects in table B share the same primary key from Table A. Here are some JSON bodies to represent each table.

        Table A
[
    {
        "pk": 1
        "count(fk)": "Cat counter",
        "name" "Jerry"
    },
    {
        "pk": 2
        "count(fk)": "Cat counter",
        "name" "Max"
    },
    {
      ...
    }
]

[        Table B
    {
        "pk": "Cat counter"
        "count": 0
    },
    {
        "pk": "Dog counter"
        "Count": 0
    }
]

Let’s say we POST all the values that represent Table A in one POST request. At the same time, I want table B to be updated with the count of cats or dogs through a save method override of Table A.

Right now I am doing it this way in Table A’s model which does update the count field as I wanted to, but it doesn’t seem to remember previous iterations, even though it is running through this method as far as I can tell (through printing to the console) for every row in Table A.

def save(self, *args, **kwargs):
    try:
        super(TableA, self).save()
        animal_count = self.count
        animal_count.count = animal_count.count + 1
        animal_count.save(update_fields=['count'])
    except Exception as e
            "blah blah" % str(e),
            status=status.HTTP_400_BAD_REQUEST,
        )

So if we were to assume that table B in the JSON body above was the table’s current state, and I posted to table A, we would get a count of 2 for cats, and 0 for dogs in table B. Instead, we get a count of 1 for cats, and 0 for dogs.

So my questions are, is there a way to make what I want to do here work? Is it some issue of the save for each object not going through until the whole POST process is complete, thus only remembering the last iteration maybe? Something else?

Appreciate any help, thanks.

Solution

The issue turned out to be that once you assign an instance of animal_count, it is stored in memory. On subsequent instances, when referencing this object, it is always what it originally was, not the updated value that got saved to the DB in a previous instance.

By putting animal_count.refresh_from_db() below animal_count = self.count our problem is solved by forcing that object to be updated to match the new version in the database.

Answered By – Disc

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published