Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django manytomany - get value from through

I have a manytomany field between 2 models:

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()

Now my problem is:

Given a coupon and a user ID, how can I get the date in which the user bought the coupon ?
Something like mycoupon.boutcoupons.filter(user=userid) and then get the date somehow..

Problem is that the field belongs to the user... and if I access the field from the user I get a list of coupons anyway, without the date.

I just need the coupon-userID .date value.

like image 820
Yochai Timmer Avatar asked Feb 24 '23 04:02

Yochai Timmer


1 Answers

Just query UserCoupons directly.

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

or use the reverse relation from Coupon:

mycoupon.usercoupon_set.get(user=myuser)

Edit in response to comment There are two separate things going on here. Firstly, a ManyToMany does get added to the other side as a set (actually, a Manager) - using the name of the source model plus _set. So in this case, Coupon will have a userprofile_set attribute.

Secondly, however, you'll see that's not what I used in my answer. That's because ForeignKeys also add reverse relation Managers to their target models. Your through model defines ForeignKeys to both userProfile and Coupon, so they both get usercoupons_set attributes.

like image 98
Daniel Roseman Avatar answered Feb 26 '23 21:02

Daniel Roseman