I have create some apps inside my Django project, they are called Coupon
and Store
, both of them are related to each other. For instance, there can be many coupons related a store (Coupon1, Coupon2 belongs to Store1).
class Coupon(models.Model):
store = models.ForeignKey(Store, on_delete=models.DO_NOTHING)
title = models.CharField(max_length=200)
...
def __str__(self):
return self.title
class Store(models.Model):
name = models.CharField(max_length=200)
description = models.TextField(blank=True)
...
def __str__(self):
return self.name
What I'd like to accomplish is when a user clicks on any of these coupons (Coupon1, Coupon2), the user should see a list of all coupons in a seperate view which is related to Store1.
How should I do it ?
If I correctly understand what you want, it's gonna be that way:
# Get the Coupon1 instance
coupon = Coupon.objects.filter(name="Coupon1")
# Get all coupons related to the same store as Coupon1
coupons_from_same_store = Coupon.objects.filter(store=coupon.store)
let's say I have the ID of the coupon in URL called coupen_id
,
coupen = Coupen.objects.get(pk=coupen_id)
coupons = Coupon.objects.filter(store_id=coupen.store.id)
print(store_id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.