Double Foreign Key in Django?

Is there a way to simulate double foreign keys in Django?

For example, if I had tables: audio, overlay, html and a table: timeline_item, which has a field identifier, and a field category that defines a sound, overlay, or html ...

Does anyone know how I will simulate this in Django? or if possible?

+3
source share
3 answers

Sounds like a polymorphic association. Perhaps you can solve your problem with a generic Django relationship using the ContentTypes framework .

+8
source

TWO​​strong > , , 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 %}
+2

Source: https://habr.com/ru/post/1795642/


All Articles