简体   繁体   English

Django的双外键?

[英]Double Foreign Key in Django?

Is there anyway to model double foreign keys in Django? 无论如何在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... 例如,如果我有表:audio,overlay,html和table:timeline_item,它有一个字段id,以及一个指定audio,overlay或html的字段类别......

Does anyone know how I would go about modeling this in Django? 有谁知道我会如何在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. 也许你可以使用ContentTypes框架解决Django的泛型关系问题。

Foreign key is referential constraint between TWO tables so you really can't have one column referencing to 3 columns on 3 different tables. 外键是两个表之间的引用约束,因此您实际上不能有一列引用3个不同表上的3列。

see: http://en.wikipedia.org/wiki/Foreign_key 请参阅: 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 我最终做的是使用这个: 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. 在此之前,我正在使用类中定义的另一个方法,该方法需要2个外键,这些外键只是将字段字典映射到它们的类并返回该对象类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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