B
B
bituke2021-06-12 09:15:42
Django
bituke, 2021-06-12 09:15:42

How to correctly design a database through Django ORM?

There is a question model:

class Question(models.Model):
  title = models.CharField(max_length=255,)
  text = models.TextField()
  author = models.ForeignKey(User, 
              on_delete=models.CASCADE, 
              related_name='author')

There is a model for answering the question (everything is the same)

There are models for the content of the question (video, text, audio):
class Content(models.Model):
    question = models.ForeignKey(Question,
                               related_name='question',
                               on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType,
                                     limit_choices_to={'model__in':('text',
                                                                    'video',
                                                                    'image',
                                                                    'file')},
                                     on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    item = GenericForeignKey('content_type', 'object_id')
    order = OrderField(blank=True, for_fields=['question'])

    class Meta:
            ordering = ['order']

class ItemBase(models.Model):
  question = models.ForeignKey(Question, on_delete=models.CASCADE)
    title = models.CharField(max_length=250, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

    def __str__(self):
        return self.title

class Text(ItemBase):
  content = models.TextField()

class File(ItemBase):
  file = models.FileField(upload_to='files')

class Image(ItemBase):
  file = models.FileField(upload_to='images')

class Video(ItemBase):
  url = models.URLField()


Note that this model only applies to the question model. How can the content model be made "abstract"? So that it can be connected to the question model, and to the answer model, and to thousands of other models, so that it connects quickly and does not need to be rewritten for each model. Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-06-12
@bituke

Either use model inheritance or generalized relationships .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question