[Answered ]-Access the rows of a model B through a list of foreign keys of B

1👍

First, the recommended way of doing this is to define a ManyToMany relation between A and B. Your current method won’t enforce referential integrity (e.g. if you delete a B instance it won’t be deleted from all A instances that refer to it). If you are able to change the database schema, and don’t have to use a JSONField I suggest you to do that instead.

That being said, you can easily implement it by adding a helper method to class A:

class A(models.Model):
    # e.g. contains [1, 5, 3, 6, 2]:
    foreignKeysOfB = models.JSONField(null = True)

    def get_b_instances(self):
        return B.objects.filter(pk__in=self.foreignKeysOfB)

Then you can simply do:

{% for my_b in my_a.get_b_instances %}
  <tr>
    <td>{{ my_b.someField }}</td>
  </tr>
{% endfor %}
👤Selcuk

Leave a comment