Evgenii Legotckoi
March 26, 2017, 11: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:

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.db import models
  4. from django.contrib.auth.models import User
  5. from django.utils.translation import ugettext_lazy as _
  6.  
  7. from ckeditor_uploader.fields import RichTextUploadingField
  8.  
  9. class PostBase(models.Model):
  10. class Meta:
  11. abstract = True # This field indicates that the class is abstract
  12.   # and that it does not need to create a table for it
  13.  
  14. SPAM = 'S'
  15. NOT_MODERATED = 'N'
  16. POST_MODERATED = 'P'
  17. MODERATED = 'M'
  18. MODERATION_CHOICES = (
  19. (SPAM, 'SPAM'),
  20. (NOT_MODERATED, 'Not Moderated'),
  21. (POST_MODERATED, 'Post Moderated'),
  22. (MODERATED, 'Moderated')
  23. )
  24.  
  25. author = models.ForeignKey(User, verbose_name=_("Author"))
  26. content = models.TextField(_('Content'), blank=True)
  27. pub_date = models.DateTimeField(_('Publication date'), blank=True, null=True)
  28. moderation = models.CharField(
  29. _('Модерация'),
  30. max_length=1,
  31. choices=MODERATION_CHOICES,
  32. default=NOT_MODERATED
  33. )

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:

  1. class Comment(PostBase):
  2. class Meta:
  3. db_table = "comments"
  4.  
  5. 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 ).

  1. class PostBaseAdmin(admin.ModelAdmin):
  2. list_display = ('content', 'author', 'pub_date')
  3. search_fields = ('content', 'author__username')
  4. list_filter = ('moderation',)
  5. actions = ['make_spam', 'make_not_moderated', 'make_post_moderated', 'make_moderated']
  6.  
  7. def moderate(self, request, rows_updated, choice_description):
  8. if rows_updated == 1:
  9. message_bit = "1 entry is marked as %s" % choice_description
  10. else:
  11. message_bit = "%s entries are marked as %s." % (rows_updated, choice_description)
  12. self.message_user(request, "%s" % message_bit)
  13.  
  14. def make_spam(self, request, queryset):
  15. self.moderate(
  16. request=request,
  17. rows_updated=queryset.update(moderation=PostBase.SPAM),
  18. choice_description="SPAM"
  19. )
  20. make_spam.short_description = "Mark selected as SPAM"
  21.  
  22. def make_not_moderated(self, request, queryset):
  23. self.moderate(
  24. request=request,
  25. rows_updated=queryset.update(moderation=PostBase.NOT_MODERATED),
  26. choice_description="NOT_MODERATED"
  27. )
  28. make_not_moderated.short_description = "Mark selected as NOT_MODERATED"
  29.  
  30. def make_post_moderated(self, request, queryset):
  31. self.moderate(
  32. request=request,
  33. rows_updated=queryset.update(moderation=PostBase.POST_MODERATED),
  34. choice_description="POST_MODERATED"
  35. )
  36. make_post_moderated.short_description = "Mark selected as POST_MODERATED"
  37.  
  38. def make_moderated(self, request, queryset):
  39. self.moderate(
  40. request=request,
  41. rows_updated=queryset.update(moderation=PostBase.MODERATED),
  42. choice_description="MODERATED"
  43. )
  44. 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:

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

For Django I recommend VDS-server of Timeweb hoster .

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html