Double Foreign Key in Django?

空扰寡人 提交于 2019-12-10 09:57:28

问题


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?


回答1:


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



回答3:


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.



来源:https://stackoverflow.com/questions/5162132/double-foreign-key-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!