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
CodePudding user response:
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.
CodePudding user response:
Hellow,
Below models.py
class Category(models.Model):
name = models.CharField(max_length=50, unique=True)
description = models.CharField(max_length=150)
class Element(models.Model):
category = models.ForeignKey(Category, related_name='elements', on_delete=models.CASCADE)
element = models.CharField(max_length=50)
class Topic(models.Model):
subject = models.CharField(max_length=255)
element = models.ForeignKey(KPI, related_name='topics', on_delete=models.CASCADE)
category = models.ForeignKey(Category, related_name='tickets', on_delete=models.CASCADE)
created_by = models.ForeignKey(User, related_name='tickets', on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
views.py
def new_topic(request, category_id):
category = get_object_or_404(Category, pk=category_id)
kpi = KPI.objects.select_related().filter(category=category_id)
#user = User.objects.first()
if request.method == "POST":
form = NewTopicForm(request.POST)
if form.is_valid():
topic = form.save(commit=False)
topic.category = category
topic.created_by = request.user
topic.save()
post = Post.objects.create(
message=form.cleaned_data.get('message'),
topic=topic
)
return redirect('category_topic', category_id=category.pk)
else:
form = NewTopicForm()
return render(request, 'new_topic.html', {'category': category, 'form':form}
)
forms.py
class NewTopicForm(forms.ModelForm):
message = forms.CharField(widget=forms.Textarea, max_length=6000)
class Meta:
model = Topic
fields = ['subject', 'issue_date', 'message', 'element']
Some elements was created by admin interface such as
Category_1 elements_1 Category_1 elemnts_2 Category_2 elements_3
The quesion is when I need to create new topic in category_1, I need to show only elements belongs to category 1 not all elements
Thank you