Asserting for presence of added objects in Django ManyToMany relation

后端 未结 2 710
时光说笑
时光说笑 2021-01-27 04:43

I have the following model;

class Station(models.Model):
    name = models.CharField(max_length=50)
    address = models.TextField(default=\'\')
    owner = mode         


        
相关标签:
2条回答
  • 2021-01-27 04:53

    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().

    0 讨论(0)
  • 2021-01-27 05:09

    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.

    0 讨论(0)
提交回复
热议问题