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.
Just query UserCoupons directly.
or use the reverse relation from Coupon:
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,Couponwill have auserprofile_setattribute.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_setattributes.