0
votes

I have the following models:

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

class Element(models.Model):

category = models.ForeignKey(Category)
name = models.CharField(max_length=255)

class Topic(models.Model):

category = models.ForeignKey(Category)

element = models.ForeignKey(Element) name = models.CharField(max_length=255)

I basically need to add New topic in catégory id =1 and get only a list of élément belongs to category 1

I have created a view New topic in category id =1, but for fields element in form i get all elements for all categories

1

1 Answers

0
votes

To do this, you should add a related_name to the category field in the Element model.

ex

category = models.ForeignKey(Category, related_name='elements')

Then when you have a topic object you can access the elements for the topic's category by doing obj.category.elements.

If you plan to get a list of posts in a category, you would do the same thing (obviously with a different name) to the FK from Topic to Category.