很多人通过

2024-05-14 07:13:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在两个模型之间有很多字段:

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)

现在我的问题是:

给定优惠券和用户ID,如何获取用户购买优惠券的日期?
mycoupon.boutcoupons.filter(user=userid)这样的东西,然后以某种方式获取日期。。

问题是该字段属于用户。。。如果我从用户那里访问这个字段,我会得到一个优惠券列表,但是没有日期。

我只需要优惠券用户名。日期值。


Tags: 用户模型modelmodelsclassuserprofile优惠券coupon
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>

直接查询用户优惠券。

UserCoupons.objects.get(user=myuser, coupon=mycoupon)

或使用与优惠券相反的关系:

mycoupon.usercoupon_set.get(user=myuser)

编辑以回应评论这里有两件事要做。首先,许多都是作为一个集合(实际上是一个管理器)添加到另一端的,使用源模型的名称加上_set。因此在本例中,Coupon将有一个userprofile_set属性。

第二,不过,你会发现我的回答中并没有用到这一点。这是因为ForeignKeys还将反向关系管理器添加到其目标模型中。你的through模型定义了用户配置文件和优惠券的外键,因此它们都得到usercoupons_set属性。

相关问题 更多 >

    热门问题