[Django]-Double Foreign Key in Django?

8👍

Sounds like a polymorphic association. Maybe you can solve your problem with Django’s generic relations using the ContentTypes framework.

2👍

Foreign key is referential constraint between TWO tables so you really can’t have one column referencing to 3 columns on 3 different tables.

see: http://en.wikipedia.org/wiki/Foreign_key

You cold make it somehow different, I believe code would be best to demonstrate:

class Category(models.Model):
  TYPES = (
    ('audio', 'audio'),
    ('overlay', 'overlay'),
    ('html', 'html'),
  )
  type = models.CharField(choices=TYPES)

class Audio(models.Model):
  category = models.OneToOneField(Category)
  additional_column_for_audio = models. ...
  #...
# same for overlay and html

class Item(models.Model):
  # id is automatically added
  category = models.ForeignKey(Category)

then you can iterate over items and do something like this:

{% for item in items %}
  {% if item.category.type == "audio" %}
     {{ item.category.audio.additional_column_for_audio }}
  {% endif %}
{% endfor %}

0👍

What I ended up doing was using this:
http://docs.djangoproject.com/en/1.0/topics/db/models/#id7

Before that I was using another method defined in the class that needed 2 foreign keys that just mapped a dictionary of fields to their classes and returned that object type.

Leave a comment