Reputation: 1013
I have two models based in which one is related to another.
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)
Here I wanted filter contacts who have atleast one phonenumber.
I have tried,
contacts = Contacts.objects.filter(user=request.user, phone_numbers__isnull=True)
Is it correct or not? Is there any other optimized method? How can we filter queryset based on related names?
Upvotes: 0
Views: 215
Reputation: 53326
I think you want,
contacts = Contacts.objects.filter(user=request.user, phone_numbers__isnull=False)
i.e check for False
rather than True
, as you want Contacts
where at least one PhoneNumber
is there. If its not there it will be NULL
.
Upvotes: 1