如何从数据库表中获取pythonDjango中的相关类别产品?

2024-09-29 23:19:06 发布

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

我在Django项目中创建了一些应用程序,它们被称为Coupon和{},它们都是相互关联的。例如,一个商店可以有很多优惠券(Coupon1,Coupon2属于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

我想实现的是当用户点击这些优惠券(Coupon1,Coupon2)时,用户应该在与Store1相关的单独视图中看到所有优惠券的列表。在

我该怎么做?在


Tags: storeselfmodeltitlemodelsdeflengthmax
2条回答

假设我在URL中有优惠券的ID,名为coupen_id

coupen = Coupen.objects.get(pk=coupen_id)
coupons = Coupon.objects.filter(store_id=coupen.store.id)
print(store_id)

如果我正确地理解了你想要什么,那就是:

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

相关问题 更多 >

    热门问题