django manytomany through

2019-05-11 03:20发布

问题:

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