2
我有两个模型,其中一个与另一个相关。Django基于相关字段的筛选器
class Contacts(BaseModel):
user = models.ForeignKey(User, related_name='contacts')
group = models.ForeignKey(ContactGroups, related_name = 'contact_list')
name = models.CharField(_("Name"), max_length = 250, null = True, blank = True)
title = models.CharField(_("Title"), max_length = 250, null = True, blank = True)
twitter = models.CharField(_("Twitter"), max_length = 250, null = True, blank = True)
facebook = models.CharField(_("Facebook"), max_length = 250, null = True, blank = True)
google = models.CharField(_("Google +"), max_length=250, null = True, blank = True)
notes = models.TextField(_("Notes"), null = True, blank = True)
image = ImageField(_('mugshot'), upload_to = upload_to, blank = True, null = True)
class PhoneNumbers(BaseModel):
contact = models.ForeignKey(Contacts, related_name='phone_numbers')
phone = models.CharField(_("Phone"), max_length = 200, null = True, blank = True)
type = models.CharField(_("Type"), max_length = 200, choices = TYPES, null = True, blank = True)
在这里,我想过滤器联系人至少有一个phonenumber。
我都试过了,
contacts = Contacts.objects.filter(user=request.user, phone_numbers__isnull=True)
是否正确与否?有没有其他优化的方法?我们如何过滤基于相关名称的查询集?
您是否通过访问Phonenumber模型中的数据来尝试它。因此,您可以让所有联系人都有电话号码,然后尝试将所有联系人对象添加到字典中,以避免联系人将字词键和电话号码作为值重复使用(值可以是任何您需要的) –
此方法将输出正确的答案,但它需要更多的查询。这将需要更多的时间 –