如何从模型内部访问模型字段的值?

2024-03-28 21:43:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道,如何在单个模型中将一个字段值传递给另一个字段值。我需要过滤Rating对象以获得产品的平均评级,并且我希望它与其他未来的统计数据在ProductStat中。你知道吗

我的过滤尝试,由于一些"Models aren't loaded yet"的程序错误,它不允许我进行迁移,但是如果我注释掉avgRating,它就可以工作了。你知道吗

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)

所以我的问题是:如何通过ProductStat.product过滤评级?你知道吗


Tags: 模型defaultmodelmodelsproductclass段值rating
1条回答
网友
1楼 · 发布于 2024-03-28 21:43:49

当您的模型文件被解释时,Rating模型不存在。另外,您不应该使用fuctions作为默认值,而是使用callable。你知道吗

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可以帮上忙。您也可以在Django的页面中检查docs。你知道吗


如果需要使用currenntProductStat对象中的值,可以使用signal。在你的型号.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)

相关问题 更多 >