Django多对多相关名称

时间:2018-05-25 08:24:28

标签: python django

enter image description here

  <table style="width: 70%" border="0">
                <tr valign="top" >
                    <td style="width:10px">And<br /> And</td>
                    <td style="width:20px;text-align:left; "> 
                        aaaaaaaaaaaaaaaaaaaaa:
                        <br />
                         bbbbbbbbbbbbbbbbbb
                        <br />
                         cccccccccccccccccccc
                    </td>
                    <td  style="width:70px;text-align:left;">
                                    <input type="text" name="lname">
                    </td>
                </tr>
            </table>   
当我输入class Profile(models.Model): user = models.OneToOneField(User) followers = models.ManyToManyField(User, related_name='is_following', blank=True) activation_key = models.CharField(max_length=120, blank=True, null=True) activated = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ProfileManager() def __str__(self): return self.user.username 时,在shell中输入

,当我输入User.profile.followers.all()时,我会收到不同的结果。

1 个答案:

答案 0 :(得分:0)

首先,我要改变:

followers = models.ManyToManyField(User

followers = models.ManyToManyField(Profile

然后,如果您尝试打印

 user1 = Profile.objects.create() #missing args but you don't need it for the example
 user2 = Profile.objects.create()
 user1.followers.add(user2)
 user1.followers.all() 

你会得到:

[user2]

但如果你这样做

 user1.is_following.all() 

你会得到:

[]

最后,如果你这样做:

user2.is_following.all() 

结果将是:

[user1]

related_name允许您将对象放在另一个对象中。