D
D
Dmitry2022-02-13 19:55:42
Python
Dmitry, 2022-02-13 19:55:42

How to correctly form a model for an article (post)?

We have an article about programming, the article has a title (that is, its main topic), a section to which this article belongs (category), inside the article there is text (sections) with examples in the form of images and code.

Question: How to correctly form models for such an article, so that, among other things, you can still work with information in the template .

from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=400, verbose_name='Раздел')

class Article(models.Model):
    title = models.CharField(max_length=400, verbose_name='Тема статьи')
    category = models.ForeignKey(Category, on_delete=models.PROTECT)

class Section(models.Model):
    title = models.CharField(max_length=255, verbose_name='Заголовок раздела')
    text = models.TextField(blank=True, verbose_name='Текст раздела')
    article = models.ForeignKey(Article, on_delete=models.CASCADE)

class Photo(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    section = models.ForeignKey(Section, on_delete=models.CASCADE)
    photo = models.ImageField(upload_to=f"photos/{article.name}", verbose_name='Фотография')

class Code(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    section = models.ForeignKey(Section, on_delete=models.CASCADE)
    code = models.TextField(blank=True, verbose_name='Код')


As I wrote above, the article will contain many examples of code and images that need not only be displayed in the right place, but also stylistically arranged. The main content of the article, although it is a continuous text, is still divided into sections

. It turns out that:
  • There is a Category model - the topic to which the article belongs
  • a general post model containing only its title. Related by key to Category
  • Section, respectively, will contain the title and text of the section
  • Below is a model for a photo and a code, they are associated with a specific section by keys, and when displaying the template, it will be possible to check that if the photo and code refer to the section id, then they must be displayed


How generally correct is such a decision?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Nesterov, 2022-02-13
@AlexNest

Well, at least the FK to the article in the code and photos is superfluous.
PS When uploading files, it's better to generate random names for them

import uuid
import os

def get_file_path(instance, filename):
    ext = filename.split('.')[-1]
    filename = f'{uuid.uuid4()}.{ext}'
    return os.path.join('folder_path', filename) # folder_path - нужная папка (article, по идее можно вытянуть из instance)
...
...upload_to=get_file_path

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question