0

I want to combine attributes from two different models, which are connected with a ForeignKey, in one QuerySet to display them together in a table. I tried to join them with select_related, however, the attribute from model B does not appear in my QuerySet, neither can I display it in my table. What am I doing wrong? How can I add the attribute "name" to my QuerySet from model A? Can you please help me? Thanks in advance

view.py

A.objects.select_related('b_id').filter(a_id__in='abcde')

models.py

class B(models.Model):        
    b_id = models.CharField(max_length=20, primary_key=True, unique=True)
    name = models.CharField(max_length=80)
    size = models.CharField(max_length=10)

class A(models.Model):
    a_id = models.CharField(max_length=20, primary_key=True, unique=True)
    text = models.CharField(max_length=254)
    b_id = models.ForeignKey(B)

.html

{% for entry in set %}
 <tr> <td> {{entry.a_id}} </td>
      <td> {{entry.text}} </td>
      <td> {{entry.name}} </td></tr>
jules_123
  • 33
  • 6

2 Answers2

0

select_related() doesn't combine fields from two models. You should use this code to show the name property of foreign key b_id:

{{entry.b_id.name}}
catavaran
  • 44,703
  • 8
  • 98
  • 85
  • this is also not working. Still an empty table cell. `{{entry.b_id}}` would work, but not what i want to show in my table – jules_123 Jan 14 '15 at 15:44
  • It should work. May be there is no data in `name` field of `b_id`? Or you misspelled attribute name? – catavaran Jan 14 '15 at 15:52
  • I checked the spelling. I also can see the data in the table, when I login as admin. Could there be another reason? – jules_123 Jan 14 '15 at 16:00
  • Hm. Try to execute this python code: `A.objects.select_related('b_id').filter(a_id__in='abcde').first().b_id.name` – catavaran Jan 14 '15 at 16:10
0

To my understanding you need to display B model instances that are related to class A via foreign key.

Your views.py:

    A.objects.filter(a_id__in='abcde')

Your html:

    {% for entry in set %}
        <tr> <td> {{entry.a_id}} </td>
        <td> {{entry.b_id.text}} </td>
        <td> {{entry.b_id.name}} </td></tr>
garmoncheg
  • 867
  • 11
  • 26