django - 如何将唯一的约束一起回调为字段 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
模型访问吗?谢谢你 ..
解决方案
如果要计算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_persons
Visitor
推荐阅读
- reactjs - TypeError: undefined is not an object (评估 '_props$route$params$d.id')
- python - 在 VANET 中实施女巫攻击时需要考虑哪些因素
- c++ - 可以写“使用 std::vector;”吗?在标题中?而不是写 std::vector
v 每次? - python - 用于打印aws elb日志的基于python的logparser的正则表达式?
- c - 线程基数排序不快
- python - 从pandas df创建networkx图,列条目作为邻居元组
- javascript - 使用 getElementsByClassNames() 获取元素时添加 EventLinsters
- python-3.x - UnicodeDecodeError: 'utf-8' codec can't decode byte 0xf6 in position 1: invalid start byte - 试图将 DES 编码数据转换为 UTF-8 字符串
- azure - Azure Functions Blob 触发器替代方案
- php - 限制对 Google API 的 API 访问不起作用