开发者

Double Foreign Key in Django?

开发者 https://www.devze.com 2023-02-14 10:01 出处:网络
Is there anyway to model double foreign keys in Django? For instance if I had t开发者_如何学Goables: audio, overlay, html

Is there anyway to model double foreign keys in Django?

For instance if I had t开发者_如何学Goables: 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消