【问题标题】:Query Using Django ORM Many To Many field使用 Django ORM 查询多对多字段
【发布时间】:2013-06-13 17:08:03
【问题描述】:

我正在尝试使用 Django ORM 对我的 bd 进行查询,但我需要一些帮助。

型号:

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 联系人列表中。如何使用 django ORM 进行此查询?

【问题讨论】:

    标签: python sql django orm


    【解决方案1】:

    正确的解决方法是:

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

    【讨论】:

      猜你喜欢
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多