Spatial Digger
Spatial Digger

Reputation: 1993

Django, adding two foreign keys to the same model

I have a table which relates one row in the Context table to another row in the Context table. In Django I try to add two foreign keys and it says I need to use related name. I've been reading the documentation on related name but I cannot understand it. I include the working model below with commented out rows. Following I also include the template. Can anyone fix the code below?

model.py

class Relationship (models.Model):
    relationship_id = models.AutoField(primary_key=True)
    # context_id1 = models.IntegerField()
    context_id1 = models.ForeignKey(Context, db_column='context_id1', on_delete = models.PROTECT)
    context_id2 = models.IntegerField()
    # context_id2 = models.ForeignKey(Context, db_column='context_id2', on_delete = models.PROTECT)
    relationship = models.CharField(max_length = 50, blank=True, null=True)

template

  {% for relationship in context.relationship_set.all %}
      Current Context:{{relationship.context_id1.number}} <br> # works
      Relationship:{{relationship.relationship}} <br> # works
      Related Context: {{relationship.context_id2.number}} # fails
  {% endfor %}

Upvotes: 1

Views: 73

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476614

The related_name=… [Django-doc] is the name of your relation "in reverse". So from a Context to a Relationship. Since you here target the same model twice, the two can not be named both relationship_set. You thus can give these different related_names. For example:

class Relationship(models.Model):
    id = models.AutoField(primary_key=True, db_name='relationship_id')
    context1 = models.ForeignKey(
        Context,
        db_column='context_id1',
        on_delete = models.PROTECT,
        related_name='relations_through1'
    )
    context1 = models.ForeignKey(
        Context,
        db_column='context_id1',
        on_delete = models.PROTECT,
        related_name='relations_through2'
    )
    relationship = models.CharField(max_length = 50, blank=True, null=True)

Note: Normally one does not add a suffix _id to a ForeignKey field, since Django will automatically add a "twin" field with an _id suffix. Therefore it should be context1, instead of context_id1.

Upvotes: 1

Related Questions