我想在我的 html 模板中显示其父项下的所有子对象。如何在 Django 中做到这一点?
#html
{%for i in contact %}
{% if not i.parent %}#shwing only parent objects
ticket #parent_id{{i.message}}
#here I want to list all child object of my parent
{%endif%}
{%endfor%}
这是我的models.py:
class Contact(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True,related_name='contact_user')
name = models.CharField(max_length=250)
email = models.EmailField(max_length=500)
message = models.CharField(max_length=2000,blank=True,null=True)
parent =models.ForeignKey('self', on_delete=models.CASCADE,
null=True, blank=True, related_name='contact_parent')
sno = models.AutoField(primary_key=True,)
这是我的views.py
def UserProfileView(request):
userinfo = UserManagement.objects.filter(username=request.user)
userprofile = UserProfile.objects.filter(user=request.user)
contact = Contact.objects.filter(user=request.user)
form = TicketForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form.instance.user = request.user
messages.add_message(request, messages.INFO,'You ticket submitted sucessfully')
form.save()
return redirect('members:user-profile-private')
else:
form = TicketForm()
context={"userinfo":userinfo,"userprofile":userprofile,"form":form,"contact":contact}
return render(request,"members/privateprofile.html",context)
答案 0 :(得分:0)
我认为您正在寻找以下内容:
查询:
Contact.objects.filter(parent__isnull=True)
模板:
{% for parent in contact %}
<h1>{{ parent.name }}</h1>
{% if parent.contact_parent.count %}
<ul>
{% for child in parent.contact_parent.all %}
<li>{{ child.name }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
此外,我认为您应该将 related_name
更改为类似 contact_children
或仅 children
,记住这应该代表 OneToMany 关系中的字段的相反内容,例如:
parent = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="contact_children", # opposite of field
)
为了避免在模板中进行过多查询,您可以使用 prefetch_related
:
Contact.objects.prefetch_related('contact_children').filter(parent__isnull=True)
和模板:
{% for parent in contact %}
<h1>{{ parent.name }}</h1>
{% if parent.contact_children.count %}
<ul>
{% for child in parent.contact_children.all %}
<li>{{ child.name }}</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
看起来更容易理解吧?