2012-10-16 3 views
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) 

여기 적어도 하나의 전화 번호가있는 필터 연락처가 필요했습니다.

내가 시도

,

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

그것은 올바른지인가? 다른 최적화 된 방법이 있습니까? 어떻게 관련 이름을 기반으로 쿼리 세트를 필터링 할 수 있습니까? 난 당신이 원하는 생각

+2

Phonenumber 모델의 데이터에 액세스하여 사용해 보셨습니까? 따라서 모든 연락처에 전화 번호를 부여한 다음 사전에 모든 연락처 개체를 사전에 추가하여 연락처와 연락처가 중복되지 않도록하고 값으로 전화 번호를 입력하십시오 (값은 무엇이든 될 수 있음) –

+0

이 메서드는 정답을 출력합니다 ,하지만 더 많은 쿼리가 필요합니다. 훨씬 더 많은 시간이 필요할 것입니다. –

답변

1

, False보다는 True에 대한

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

즉 검사, 적어도 하나의 PhoneNumber가 어디 Contacts을 원하는대로. 그곳에 없다면 NULL이 될 것입니다.