首页 > 解决方案 > 如何将唯一的约束一起回调为字段 django

问题描述

我正在尝试回调唯一约束字段,在我的项目中我必须计算所选 M2M 的数量

class Booking(models.Model):
    room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms')
    takes_by = models.ManyToManyField(Vistor)

    @property
    def no_persons(self):
        qnt =  Booking.objects.filter(takes_by__full_information=self).count()#but this doesnt  work
        return qnt

无法查询“部分房间信息”:必须是“Vistor”实例。

class Vistor(models.Model):
    full_name = models.CharField(max_length=150)
    dob = models.DateField(max_length=14)
    city = models.ForeignKey(City,on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['full_name','dob','city'],name='full_information')
        ]

    def __str__(self):
        return f'{self.full_name} - {self.city} - {self.dob}'

可以full_information通过Booking模型访问吗?谢谢你 ..

标签: djangounique-constraint

解决方案


如果要计算Visitor与该预订相关的 s 数,可以使用以下方法计算:

@property
def no_persons(self):
    self.taken_by.count()

这将对数据库进行额外的查询,因此最好让数据库在查询中计算这些。因此,您可以删除该属性,并使用以下命令进行查询:

from django.db.models import Count

Booking.objects.annotate(
    no_persons=Count('takes_by')
)

由此Booking产生的 s将具有与相关 s 数量相关的QuerySet额外属性。no_personsVisitor


推荐阅读