繁体   English   中英

如何获取 django 中与外键相关的所有项目?

[英]How to get all items related to a Foreign Key in django?

我的目标是从我创建的 model 中获取具有特定类别的所有项目。 例如,如果我应该获得一个带有 ID 的类别,我想获得该类别中的所有产品。

下面是我的model

class Product(models.Model):
    name = models.CharField(max_length=200)
    category = models.ForeignKey('Category', null=True, on_delete=models.SET_NULL)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

    def __str__(self):
        return self.name

class Category(models.Model):
    #product = models.ForeignKey('Product', null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=200, blank=True, null=True)
    id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

    def __str__(self):
        return self.name

以下是我的看法

def getCategory(request, pk):
    category = Category.objects.get(id=pk)
    # product = Product.objects.all()
    products = Product.category_set.all()
    # Product.category_set.all()
    context = {'category': category, 'products':products}
    return render(request, '*.html', context)

我尝试使用 Product.category_set.all() 并尝试将其翻转过来,让产品与我获得 ID 的类别相关,但我不知道该怎么做。

我在我的模板中使用了下面的这个循环并且它有效但我想知道是否有更好的方法来做到这一点。

模板

{% for product in products %}

{% if product.category.id == category.id %}

View
def getCategory(request, pk):
    category = Category.objects.get(id=pk)
    products = Product.objects.all()
    context = {'category': category, 'products':products}
    return render(request, 'products/shop.html', context)

您可以使用与主要 model 关联的次要 model(产品)的字段(类别)到 select 以及主要 model (类别)的标识符。 为此,请指定此字段,并通过双下划线指定主要 model 的所需字段。

Product.objects.filter(category__id=pk)
products = Product.objects.filter(category=Category.objects.get(id=1))

我猜?

https://docs.djangoproject.com/en/4.1/ref/models/querysets/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM