问题描述
如果我有两个模型与一个通过模型有很多关系,那么我如何从通过表中获取数据。
class Bike(models.Model):
nickname = models.CharField(max_length = 40)
users = models.ManyToManyField(User,through ='bike.BikeUser')
BikeUser类
class BikeUser(models.Model):
bike = models.ForeignKey(Bike)
user = models.ForeignKey(User)
comment = models.CharField(max_length = 140)
我会添加一个用户到那辆自行车(假设我有一个myBike和一个myUser已经) >
BikeUser.objects.create(bike = myBike,user = myUser,comment ='在一个花哨的商店获得这个)
我可以通过myBike.users.all()获取所有的用户,但是如何获得'comment'property?
我想做某事喜欢myBike.users.all():
打印myBikeUser.comment
code>
解决方案通过表与标准ForeignKeys链接,所以你做一个普通的ForeignKey查找。不要忘记每个自行车用户有一个评论,也就是每个自行车/用户配对的评论。 myBike.bikeuser_set.all()中的myBikeUser
打印myBikeUser.comment,myBikeUser.user.first_name
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
解决方案 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
这篇关于django manytomany通过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!