Evgenii Legotckoi
Evgenii LegotckoiMarch 26, 2017, 1:45 a.m.

Django - Tutorial 021. Model Inheritance, Abstract Model

After refactoring on the site, four main entities were identified, in which common properties were identified, namely:

  • Article - articles
  • Comment - comments
  • ForumTopic - Forum themes (questions)
  • ForumPost - Answers to forum topics

Of course, and so it was clear that these entities can have the same data fields, the same methods, etc. But when developing this site, I myself simultaneously study Python and Django. Therefore, the project has the character of chaotic introduction of small ToDo with subsequent refactoring in the study of the best approaches. Therefore, after studying the inheritance capabilities of models in Django, one general abstract data model was identified, PostBase , which has four fields that are repeated in all the above modeled models.

There is one important point here: A model that is declared abstract will not create a table in the database.

To create an abstract model, you must set the abstract variable to True for the Meta class.


PostBase

PostBase is a basic abstract model. In this abstract data model, four fields were identified that are common to the above models:

  • author - Author of an article, comment, topic or answer;
  • content - content;
  • pub_date - Publication date;
  • moderation - Moderation, all content can have four possible options:
  • SPAM - No comments;
  • NOT_MODERATED - Unverified entry, in this case, articles of users with this status will not be available to other users before moderation;
  • POST_MODERATED - approval after publishing an article user will be available to other users after publication, but it has not passed moderation;
  • MODERATED - The record was moderated.

The declaration of this abstract model will be as follows:

# -*- coding: utf-8 -*-

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _

from ckeditor_uploader.fields import RichTextUploadingField

class PostBase(models.Model):
    class Meta:
        abstract = True    # This field indicates that the class is abstract 
                           # and that it does not need to create a table for it

    SPAM = 'S'
    NOT_MODERATED = 'N'
    POST_MODERATED = 'P'
    MODERATED = 'M'
    MODERATION_CHOICES = (
        (SPAM, 'SPAM'),
        (NOT_MODERATED, 'Not Moderated'),
        (POST_MODERATED, 'Post Moderated'),
        (MODERATED, 'Moderated')
    )

    author = models.ForeignKey(User, verbose_name=_("Author"))
    content = models.TextField(_('Content'), blank=True)
    pub_date = models.DateTimeField(_('Publication date'), blank=True, null=True)
    moderation = models.CharField(
        _('Модерация'),
        max_length=1,
        choices=MODERATION_CHOICES,
        default=NOT_MODERATED
    )

Thus, it is possible to shorten the program code of the project and add the possibility of reusing duplicate code.

The structure of the model, for example, for comments, can now look like this:

class Comment(PostBase):
    class Meta:
        db_table = "comments"

    article = models.ForeignKey(Article)

The author, pub_date, content, and moderation fields are no longer required because they are present in the PostBase class. The main thing is not to enter into your model fields with the same names as in the PostBase model.

PostBaseAdmin

Also an obvious plus is that you can also exactly make one common for all classes setting the admin panel.

We will, for example, display fields, configure the search and filter content and the ability to set the status of moderation (that is, add the appropriate actions ).

class PostBaseAdmin(admin.ModelAdmin):
    list_display = ('content', 'author', 'pub_date')
    search_fields = ('content', 'author__username')
    list_filter = ('moderation',)
    actions = ['make_spam', 'make_not_moderated', 'make_post_moderated', 'make_moderated']

    def moderate(self, request, rows_updated, choice_description):
        if rows_updated == 1:
            message_bit = "1 entry is marked as %s" % choice_description
        else:
            message_bit = "%s entries are marked as %s." % (rows_updated, choice_description)
        self.message_user(request, "%s" % message_bit)

    def make_spam(self, request, queryset):
        self.moderate(
            request=request,
            rows_updated=queryset.update(moderation=PostBase.SPAM),
            choice_description="SPAM"
        )
    make_spam.short_description = "Mark selected as SPAM"

    def make_not_moderated(self, request, queryset):
        self.moderate(
            request=request,
            rows_updated=queryset.update(moderation=PostBase.NOT_MODERATED),
            choice_description="NOT_MODERATED"
        )
    make_not_moderated.short_description = "Mark selected as NOT_MODERATED"

    def make_post_moderated(self, request, queryset):
        self.moderate(
            request=request,
            rows_updated=queryset.update(moderation=PostBase.POST_MODERATED),
            choice_description="POST_MODERATED"
        )
    make_post_moderated.short_description = "Mark selected as POST_MODERATED"

    def make_moderated(self, request, queryset):
        self.moderate(
            request=request,
            rows_updated=queryset.update(moderation=PostBase.MODERATED),
            choice_description="MODERATED"
        )
    make_moderated.short_description = "Mark selected as MODERATED"

If you want to extend the filter sheets or add actions for one of the models, you can inherit from PostBaseAdmin as follows:

class ArticleAdmin(PostBaseAdmin):
    # Or completely redefine the displayed fields or fields for search
    list_display = ('title', 'section', 'author', 'pub_date', 'views', 'moderation')
    search_fields = ('title', 'author__username', 'section__title')
    # Or add to the existing list the additional list
    list_filter = PostBaseAdmin.list_filter + ('status', 'section')
    # In the case of actions, such an announcement will simply add new actions to existing ones
    actions = ['publish', 'unpublish']

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 11:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 11:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 11:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 9, 2024, 2:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 6:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 4:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 5:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 12:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 2:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 1:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 9:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 11:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks