简体   繁体   中英

Double Foreign Key in Django?

Is there anyway to model double foreign keys in Django?

For instance if I had tables: audio, overlay, html and the table: timeline_item which has a field id, and a field category which specifies audio, overlay, or html...

Does anyone know how I would go about modeling this in Django? or if it's even possible?

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

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 %}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM