Home > database >  How to display the information contained in a related model's field in Django template
How to display the information contained in a related model's field in Django template

Time:10-09

In my application I have the following two models:

class CondRecordHdr(models.Model):
    cond_prices_id = models.AutoField(primary_key=True, verbose_name='Cond ID')
    cond_type = models.ForeignKey(AlliedPriceCondType, ...
    material = models.ForeignKey(Material, ...

class Dependency(models.Model):
    cond_dependency = models.AutoField(primary_key=True, ...
    prc_cond_hdr = models.ForeignKey(CondRecordHdr, ...
    prc_select_obj = models.CharField(max_length=15, ...

I am placing the objects of the first model in the listview with:

class CondRecListView(ListView):
    context_object_name = 'obj_context'
    model = CondRecordHdr 
    template_name = ...

    def get_queryset(self):
       return CondRecordHdr.objects.order_by(...

Then I am using the context object to display the data in a tabular form in the template.

I am displaying the data like this:

Cond Type Material Dependency (Note1) Xyz More fields
TCHG Mouse blank abc1
IPRO Keyboard abc2

Note 1: In this column I want to display the value of field prc_select_obj model Dependency, where I have no data being displayed currently (blank).

How do I display the information contained in model Dependency in the same template (in column shown above Note1)?

CodePudding user response:

you can access to the related model Dependency from CondRecordHdr in a template by the name set in the field with param related_name:

prc_cond_hdr = models.ForeignKey(CondRecordHdr, related_name="dependencies",...)

# And in the template
{% for obj in obj_context %}
{% for dep in obj.dependencies.all %}
{{dep.prc_select_obj}}
{% endfor %}
{% endfor %}

Without related_name set in the field, the default related_name is set to MODENAME_set, in your case: {% for dep in obj.dependency_set.all %}

More detail in the official documentation: https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.ForeignKey.related_name

  • Related