django 多对多 - 从中介表获取值
我有两个模型之间的多对多关系:
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)
,然后以某种方式获取日期……
问题是,这个字段属于用户……如果我从用户那里访问这个字段,我得到的只是优惠券的列表,而没有日期。
我只需要优惠券和用户ID对应的日期值。
3 个回答
-2
我知道这个问题已经很久了,不过我想给出一个简单明了的答案,因为我自己在解决这个问题时遇到了很多困难,网上也找不到帮助,所以我把这个分享出来,希望能帮助到和我一样的人。
Models.py
------------------------
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)
View.py
-----------------
def result(request):
a = userProfile.objects.all()
b = Coupon.objects.all(name=a.boughtCoupons.all.0)
c = UserCoupons.objects.all(coupon=c.name.all.0)
context = {'a':a,'b':b,'c':c}
return render(request,'index.html',context)
intex.html
--------------------
*your Html declaration
* content
{%for dtl in c%}
<table>
<tr>
<th>coupon</th>
<th>UserID</th>
<th>Date</th>
</tr>
<tr>
<td>{{c.coupon}}</td>
<td>{{c.user}}</td>
<td>{{c.date}}</td>
</tr>
</table>
0
我想在这里提一个观点。我知道这个问题已经被Daniel回答过了:
你可以通过下面的代码来访问“date”这个属性:
mycoupon.boutcoupons.filter(usercoupons__date="***")
12
直接查询 UserCoupons 就可以了。
UserCoupons.objects.get(user=myuser, coupon=mycoupon)
或者可以从 Coupon 反向查询:
mycoupon.usercoupon_set.get(user=myuser)
根据评论进行编辑 这里有两个不同的事情。首先,ManyToMany 关系会在另一边作为一个集合(实际上是一个管理器)被添加,使用源模型的名称加上 _set
。所以在这个例子中,Coupon
会有一个 userprofile_set
属性。
其次,你会发现我在回答中并没有使用这个。这是因为外键(ForeignKeys)也会为它们的目标模型添加反向关系管理器。你的中间模型同时定义了指向 userProfile 和 Coupon 的外键,所以它们都会有 usercoupons_set
属性。