断言Django ManyToMany关系中是否存在添加的对象

时间:2015-05-13 07:18:00

标签: django many-to-many

我有以下型号;

class Station(models.Model):
    name = models.CharField(max_length=50)
    address = models.TextField(default='')
    owner = models.ForeignKey(User,default='')
    members = models.ManyToManyField(User, related_name='members')        

现在在以下代码之后;

user1 = User.objects.create_user(username="username1",
                                     password="password1")
user1.save()
user2 = User.objects.create_user(username="username2",
                                     password="password2")
user2.save()
user3 = User.objects.create_user(username="username3",
                                     password="password3")
user3.save()
station = Station(name="somename",                            
                  address="someaddress",
                  owner=user1,
)
station.save()

station.members.add(user2,user3)

我想声称添加的用户确实存在于"成员" " Station"

有人请告诉我如何

assert station.members == [user2,user3]不会飞。 station.members实际上是<Station: Station object>.members

2 个答案:

答案 0 :(得分:0)

station.members是一名经理,即它是相关用户查询的访问者。您需要实际执行查询:在这种情况下,station.members.all()

答案 1 :(得分:0)

您的代码存在一些问题,这是我的控制台中的输出:

>>> station.members
<django.db.models.fields.related.ManyRelatedManager object at 0x110774b10>

station.members是ManyRelatedManager,而不是user2和user3的列表。

station.members.all()将返回user2和user3的列表,但是station.members.all()是QuerySet而不是列表:

>>> type(station.members.all())
<class 'django.db.models.query.QuerySet'>

所以做assert station.members.all() == [user2, user3]永远不会是真的。