简体   繁体   中英

How to list objects that have the same ForeignKey attribute?

I want to list all approval steps that have the same approval_id on one page. I can list every ApprovalSteps in my views but that is not what I want. For example, I have an approval object with ApprovalProcess id is 1. I want to list all approval steps with approval_id = 1 in my template. How can I do that?

models.py

class ApprovalProcess(models.Model):
    id = models.AutoField(primary_key=True)
    user_id = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='starter')
    doc_id = models.ForeignKey(Pdf, on_delete=models.CASCADE, null=True)
    ...


class ApprovalSteps(models.Model):
    approval_id = models.ForeignKey(ApprovalProcess, on_delete=models.CASCADE, null=True)
    starter = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, related_name='step_starter')
    ...

views.py

def approval_details(request, pk):
    approval_item = get_object_or_404(ApprovalSteps, id=pk)
    return render(request, 'approval_details.html', {'approval_item': approval_item})

You can change your approval_details view function to

def approval_details(request, pk):
    approval_items_list = get_list_or_404(ApprovalSteps, approval_id=pk)
    return render(request, 'approval_details.html', {'approval_items_list': approval_items_list})

Refer here

To access the related objects ApprovalProcess to ApprovalSteps , you can use _set ( Django Docs ).

So in your case in you template approval_item.approval_id_set.all :

{% for item in approval_item.approval_id_set.all %}
    {{ item.doc_id }}
{% endfor %}

in views.py:

approval_item.approval_id_set.all()

Or use ForeignKey.related_name :

approval_id = models.ForeignKey(
    ApprovalProcess, on_delete=models.CASCADE, null=True, 
    
)
# then you can use 


Also I recommend you to rename approval_id to approval because:

Behind the scenes, Django appends "_id" to the field name to create its database column name, see Django ForeignKey

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM