基于Django相关字段的过滤器

时间:2012-10-16 06:06:14

标签: django django-models django-queryset

我有两个模型,其中一个与另一个相关。

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)

在这里,我希望过滤联系人至少有一个电话号码。

我试过了,

contacts = Contacts.objects.filter(user=request.user, phone_numbers__isnull=True)

是否正确?还有其他优化方法吗?我们如何根据相关名称过滤查询集?

1 个答案:

答案 0 :(得分:1)

我想你想要,

contacts = Contacts.objects.filter(user=request.user, phone_numbers__isnull=False)

即检查False而不是True,因为您需要Contacts,其中至少有一个PhoneNumber。如果不存在,则为NULL