问题
I have the following model;
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')
Now after the following code;
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)
I want to assert that the added users are indeed there as the "members" of "Station"
Someone please tell me how
assert station.members == [user2,user3]
doesn't fly. station.members actually is <Station: Station object>.members
instead.
回答1:
station.members
is a Manager, i.e. it is the accessor for queries on the related users. You need to actually perform a query: in this case, station.members.all()
.
回答2:
A few issues with your code, this is the output in my console:
>>> station.members
<django.db.models.fields.related.ManyRelatedManager object at 0x110774b10>
station.members is a ManyRelatedManager rather than a list of user2 and user3.
station.members.all() will return you a list of user2 and user3, but station.members.all() is a QuerySet instead of a list:
>>> type(station.members.all())
<class 'django.db.models.query.QuerySet'>
So doing assert station.members.all() == [user2, user3]
will never be True.
来源:https://stackoverflow.com/questions/30208159/asserting-for-presence-of-added-objects-in-django-manytomany-relation