2013-06-13 1 views
2

장고 ORM을 사용하여 bd에 쿼리를 작성하려고하는데 도움이 필요합니다.Django ORM을 사용하여 쿼리 Many To Many 필드

모델 :

class Participant(models.Model): 
    username = models.CharField(max_length=20) 
    username.primary_key = True 
    #password = models.CharField(max_length=128) 
    work_place = models.CharField(max_length=50) 
    photo = models.FileField(upload_to='user_photo') 
    name = models.CharField(max_length=30) 
    country = models.CharField(max_length=20) 
    phone_number = models.IntegerField(max_length=9) 
    email = models.EmailField(unique = True) 
    qrcode = models.FileField(upload_to = 'qrcodes',null=True,blank=True) 
    contact = models.OneToOneField('Contact', related_name= 'participant_contact') 
    user = models.OneToOneField(User) 
    contacts = models.ManyToManyField('Contact', related_name='contact_list', null=True, blank=True) 


    def save(self, *args, **kw): 
     self.username = self.user.username 
     c= Contact() 
     c.save() 
     self.contact = c 
     super(Participant, self).save(*args, **kw) 

    def __unicode__(self): 
     return self.username 

class Contact(models.Model): 
    id = models.AutoField(primary_key=True) 

나는 주어진 참가자의 연락처 모든 참가자를 얻기 위해 필요

예 :

Contact Table: | id | 
       |_______|  
       | 1  | 
       | 2  | 

Participant Table: |username|...|participant_contact| 
        |_______ |___|___________________|     
        | test | |  1   | 
        | test2 | |  2   | 

Contacts Relation: |id_Participant1|id_participant_2| 
        |_______________|________________|     
        | 1    | 2    | 


> p1 = Participant.objects.get(username="test") 
> p2 = Participant.objects.get(username="test2") 

그래서 p2p1 연락처 목록에 있습니다. 어떻게 장고 ORM이 쿼리를 만들 수 있습니까?

답변

2

정확한 솔루션이다

> Participant.objects.filter(contact__in= p1.contacts.all())