0

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

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)

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

4

1 回答 1

1

我想你想要,

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

即检查False而不是True,因为你想要Contacts那里至少有一个PhoneNumber。如果它不存在,它将存在NULL

于 2012-10-16T06:27:04.243 回答