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模型中的數據來嘗試它。因此,您可以讓所有聯繫人都有電話號碼,然後嘗試將所有聯繫人對象添加到字典中,以避免聯繫人將字詞鍵和電話號碼作爲值重複使用(值可以是任何您需要的) –
此方法將輸出正確的答案,但它需要更多的查詢。這將需要更多的時間 –