I have django models with a manytomany connection with a through class:
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)
I know how I can get each of them individually using and ID or something to filter.
But, I need to get the Through table’s value with all the user’s details (profile).
So how can I do something like a JOIN, and get a UserCoupons + userProfile pair in a single query ? ( So I can get the matching user profile without an extra query ?)
You can query directly on
UserCouponsand useselect_related()to fetch also the related objects in one query:Note that
select_related()doesn’t work “backwards”. That’s why you need to use a manager of the class that defines theForeignKeyto make it work (UserCouponsin this case).