Yoc*_*mer 2 python django django-models
我有两个模型之间的多个领域:
class userProfile(models.Model):
boughtCoupons = models.ManyToManyField(Coupon, through='UserCoupons')
class UserCoupons(models.Model):
user = models.ForeignKey(userProfile)
coupon = models.ForeignKey(Coupon)
date = models.DateField()
class Coupon(models.Model):
name = models.CharField(max_length=10)
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:
给定优惠券和用户ID,我如何获得用户购买优惠券的日期?
有点像mycoupon.boutcoupons.filter(user=userid) ,然后以某种方式得到日期..
问题是该字段属于用户...如果我从用户访问该字段,我得到一个优惠券列表,无需日期.
我只需要coupon-userID .date值.
只需直接查询UserCoupons即可.
UserCoupons.objects.get(user=myuser, coupon=mycoupon)
Run Code Online (Sandbox Code Playgroud)
或使用优惠券的反向关系:
mycoupon.usercoupon_set.get(user=myuser)
Run Code Online (Sandbox Code Playgroud)
编辑以回应评论这里有两个不同的事情.首先,ManyToMany 确实作为一个集合(实际上是一个管理器)添加到另一侧 - 使用源模型的名称加上_set.所以在这种情况下,Coupon会有一个userprofile_set属性.
其次,你会发现这不是我在答案中使用的.这是因为ForeignKeys还为其目标模型添加了反向关系管理器.您的直通模型将ForeignKeys定义为userProfile和Coupon,因此它们都获得usercoupons_set属性.
| 归档时间: |
|
| 查看次数: |
5245 次 |
| 最近记录: |