Django 中的双外键?

发布于 2024-10-20 03:24:20 字数 154 浏览 2 评论 0原文

有没有办法在 Django 中模拟双外键?

例如,如果我有表格:音频、覆盖、html 以及表:timeline_item,它有一个字段 id,以及一个指定音频、覆盖或 html 的字段类别...

有谁知道我将如何在 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦魇绽荼蘼 2024-10-27 03:24:20

听起来像是多态关联。也许您可以使用 ContentTypes< 来解决 Django 通用关系的问题/a> 框架。

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

金兰素衣 2024-10-27 03:24:20

外键是两个表之间的引用约束,因此您实际上不能让一列引用3个不同表上的3列。

请参阅:http://en.wikipedia.org/wiki/Foreign_key

你冷酷地让它有所不同,我相信代码最好能够演示:

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)

然后您可以迭代项目并执行如下操作:

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

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 %}
愛上了 2024-10-27 03:24:20

我最终做的是使用这个:
http://docs.djangoproject.com/en/1.0/topics/ db/models/#id7

在此之前,我使用了类中定义的另一种方法,该方法需要 2 个外键,仅将字段字典映射到其类并返回该对象类型。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文