0

I am using DjangoREST with PostgreSQL. I have these two models: author/models.py:

class Author(models.Model):
     name = models.CharField(max_length=256)
     allsize =  models.FloatField(default=0)

and in files/models.py:

class File(models.Model):
     author =  models.ForeignKey(Author, on_delete=models.CASCADE)
     name = models.CharField(max_length=256)
     size = models.FloatField(default=0)

If I upload multiple files having the same size (from the front end), in order to update the allsize field (which is sum of the all uploaded files) of the author, DjangoREST didn't update correctly the values maybe according to the concurrency (they have same size), despite I am doing a raw sql transaction:

    with connection.cursor() as cursor:
        cursor.execute("BEGIN; set transaction isolation level read committed;"
                        "update author_author set allsize = allsize + %s where author_id = %s;",
                               [validated_data.get('size', 0), validated_data.get('author', 0)])
        cursor.execute("COMMIT;")

2 Answers 2

0

allsize field is actually a duplication of data. The information is already present in your database (the sum of all the File.size related to this user).

If you want to get this information for a given Author, you could use :

class Author(models.Model):
     name = models.CharField(max_length=256)

     def all_size(self):
        return self.aggregate(all_size=Sum('files__size')).all_size

This way, you have no data duplication, and an easy way to get your aggregate

More resources in Django docs

2
  • Yes, it works, but it is not heavy that every time the user is connected to do this aggregation?
    – Wave1988
    Commented Apr 11, 2020 at 10:34
  • It is a DB-level aggregation. Your database is made for that, except if we talk about hundred of millions of records ! Compared to the pain to maintain two several sources of truth, and properly update each one for any change, the tradeoff is OK. If you want to improve performance, you can look at 'select_related()' method Commented Apr 11, 2020 at 13:35
0

my SQL transaction works, I had a mistake in my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.