igor_alefirenko
igor_alefirenko

Reputation: 168

How to do right relationships between objects Django

I have two models: Category and Item. Item can have 2 or more categories so I need to have a relationship on categories(maybe one-to-many) from the item I create. But, I also need to fetch that items related to a category(or categories), maybe like this: http://example.com/api/items?category_id=5

Can anyone advice how can I achieve that? Thanks.

Upvotes: 0

Views: 54

Answers (3)

Akash Wankhede
Akash Wankhede

Reputation: 618

The best practice I would suggest is, add many-to-many relation of category table in your item table.

For example:

class Category(models.Model):
    # Write here your fields name

class Item(models.Model):
    categories = models.ManyToManyField(Category)

Upvotes: 1

Sijan Bhandari
Sijan Bhandari

Reputation: 3051

I believe, you have manytomany relation between Item and Category as

class Category:
    .....

class Item:
    category = ManytoMany relation to Category

In this case, you can extract Item related to category as following:

Suppose you have Category object as c1

 c1.item_set.all()

Here c1 = Category.objects.get(id=5)

Upvotes: 1

doru
doru

Reputation: 9110

Because an item may be in multiple categories and, also, a category may have multiple items between Category and Item models must be a Many-to-Many relationship which you can define as follows:

class Category(models.Model):
    name = models.CharField(max_length=30)
    .....

and

class item(models.Model):
    ....
    categories = modles.ManyToManyField(Category)

In the docs you can see more details of operations that can be performed using the Python API facilities.

Upvotes: 1

Related Questions