Home > Mobile >  How to get all items related to a Foreign Key in django?
How to get all items related to a Foreign Key in django?

Time:01-02

My aim is to get all the items with a particular category from the model I created. For example, if I should get a category with an ID, I want to get all the products that is in that category.

Below is my 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

Below is my view

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)

I tried using Product.category_set.all() and I have tried to flip it over, getting the products relaed to the category that I got the ID but I dont know how I can do that.

I used this loop below in my template and it worked but I wonder if there is a better way to do it.

Template

{% 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)

CodePudding user response:

You can use the field (category) of the secondary model (Product) associated with the primary model to select with the identifier of the primary model (Category). To do this, specify this field and, through a double underscore, the desired field of the primary model.

Product.objects.filter(category__id=pk)

CodePudding user response:

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

I guess?

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

  • Related