django manytomany through

做~自己de王妃 提交于 2019-12-07 16:38:39

问题


If I have two Models that have a manytomany relationship with a through model, how do I get data from that 'through' table.

class Bike(models.Model):
   nickname = models.CharField(max_length=40)
   users    = models.ManyToManyField(User, through='bike.BikeUser')

The BikeUser class

class BikeUser(models.Model):
   bike     = models.ForeignKey(Bike)
   user     = models.ForeignKey(User)
   comment  = models.CharField(max_length=140)

And I would add a user to that bike (presuming I have a myBike and a myUser already)

BikeUser.objects.create(bike = myBike, user = myUser, comment = 'Got this one at a fancy store')

I can get all the users on 'myBike' with myBike.users.all() but how do I get the 'comment' property?

I would like to do something like

for myBikeUser in myBike.users.all():
   print myBikeUser.comment

回答1:


The through table is linked by standard ForeignKeys, so you do a normal ForeignKey lookup. Don't forget that there's a comment for each bikeuser, ie one for each bike/user pairing.

for myBikeUser in myBike.bikeuser_set.all():
    print myBikeUser.comment, myBikeUser.user.first_name


来源:https://stackoverflow.com/questions/3833749/django-manytomany-through

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!