如何将唯一的together约束调用为字段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}'

是否可以通过CCD_ 2模型访问CCD_?非常感谢。

如果您想计算与该预订相关的Visitor的数量,您可以使用来计算这些数量

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

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

from django.db.models import Count
Booking.objects.annotate(
no_persons=Count('takes_by')
)

由该QuerySet产生的Bookings将具有额外的属性no_persons和相关的Visitors的数量。

最新更新