1

I would like to know, how to pass one field value to another within a single model. I need to filter Rating objects to get average rating of a product and I want it to be in ProductStat with other future statistics.

My attempt at filtering, which won't let me make a migration because of some "Models aren't loaded yet" appregistry error but if I comment out the avgRating it works.

class ProductStat(models.Model):
   productID = models.ForeignKey('Product')
   avgRating = models.IntegerField(
      default = Rating.objects.filter(product=productID).aggregate(Avg('rating'))['rating__avg']
      )

class Rating(models.Model):
   user = models.ForeignKey(settings.AUTH_USER_MODEL)
   product = models.ForeignKey('Product')
   rating = models.IntegerField(default = 3)

So my question is: how do I make ProductStat.avgRating filter ratings by ProductStat.product?

Zygro
  • 6,849
  • 11
  • 28
  • 43

1 Answers1

1

When your models file is interpreted Rating model does not exists. Also, you shouldn't use fuctions as default value, use a callable instead.

def avg_rating():
    return Rating.objects.filter(product=productID).aggregate(Avg('rating'))['rating__avg']

class ProductStat(models.Model):
   productID = models.ForeignKey('Product')
   avgRating = models.IntegerField(
      default = avg_rating
      )

This answer can help. You can also check docs for this in Django's page.


If you need to use values from the currennt ProductStat object you could use a signal. In your models.py:

from django.db.models.signals import pre_save

class ProductStat(models.Model):
   productID = models.ForeignKey('Product')
   avgRating = models.IntegerField()


def set_avg_rating(sender, instance, *args, **kwargs):

    avg = Rating.objects.filter(product=instance.productID).aggregate(Avg('rating'))['rating__avg']
    instance.avgRating = avg

pre_save.connect(set_avg_rating, sender=ProductStat)
Community
  • 1
  • 1
Gocht
  • 9,924
  • 3
  • 42
  • 81
  • It works for `makemigration` and `sqlmigrate`, but when I call `migrate`, I get error `NameError: name 'productID' is not defined` – Zygro Mar 21 '16 at 20:08
  • Oh sorry, I didn't see you were using a variable there, I just coy/paste this from your question, give me a chance to edit this. – Gocht Mar 21 '16 at 20:09
  • Yes, now it works! thank you so much! (you saved my bachelor thesis) – Zygro Mar 21 '16 at 20:41
  • @Zygro That's funny because I can not finish mine. Good for you. – Gocht Mar 21 '16 at 20:44
  • Well, there is still matter of updating (only after a manual save, will look into it later) and I fiddled around with the thing a bit and I don't really remember what I did... – Zygro Mar 21 '16 at 22:31