我在两个模型之间有一个 manytomany 字段:
class userProfile(models.Model):
boughtCoupons = models.ManyToManyField(Coupon, through='UserCoupons')
class Coupon(models.Model):
name = models.CharField(max_length=10)
class UserCoupons(models.Model):
user = models.ForeignKey(userProfile)
coupon = models.ForeignKey(Coupon)
date = models.DateField()
现在我的问题是:
给定优惠券和用户 ID,如何获取用户购买优惠券的日期?
类似于 mycoupon.boutcoupons.filter(user=userid)
然后以某种方式获取日期..
问题是该字段属于用户...如果我从用户那里访问该字段,我无论如何都会得到一张优惠券列表,但没有日期。
我只需要 coupon-userID .date 值。
最佳答案
直接查询UserCoupons即可。
UserCoupons.objects.get(user=myuser, coupon=mycoupon)
或使用优惠券的反向关系:
mycoupon.usercoupon_set.get(user=myuser)
编辑以回应评论 这里有两件不同的事情。首先,ManyToMany 确实作为一个集合(实际上是一个管理器)被添加到另一端——使用源模型的名称加上 _set
。所以在这种情况下,Coupon
将有一个 userprofile_set
属性。
但是,其次,您会发现这不是我在回答中使用的内容。那是因为 ForeignKeys 还向其目标模型添加了反向关系管理器。您的直通模型为 userProfile 和 Coupon 都定义了 ForeignKeys,因此它们都获得了 usercoupons_set
属性。
关于python - django manytomany - 从中获取值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6019553/