我在类别ID = 1中创建了一个新主题,但是对于表格中的字段元素,我获得了所有类别的所有元素
要做到这一点,您应该在
related_name
Element
。ex
category = models.ForeignKey(Category, related_name='elements')
然后,当您有一个主题对象时,您可以通过执行obj.category.elements
。
如果您打算获取类别中的帖子列表,则可以从主题到类别进行相同的事情(显然使用不同的名称)。,
,belowmodels.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)
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']
某些元素是由管理接口(例如
创建)category_1elements_1 类别_1 elemnts_2 类别_2elements_3
问题是当我需要在category_1中创建新主题时,我需要显示元素属于类别1的元素,不是所有元素
谢谢你