Can you access the subclass model from the superclass model in Django ORM?

Suppose I have a model inheritance set below.

class ArticleBase(models.Model):
    title = models.CharField()
    author = models.CharField()

class Review(ArticleBase):
    rating = models.IntegerField()

class News(ArticleBase):
    source = models.CharField()

If I need a list of all the articles, regardless of the type (in this case, browsers and news) sorted by heading, I can run the query in ArticleBase. Is there an easy way when I have an entry in ArticleBase to determine if it refers to a Review or News post without asking both models to see who has the foreign key of the post I'm working on?

+3
source share
4 answers

I assume that all instances of ArticleBase are instances of subclasses of ArticleBase.

ArticleBase , . , .

from django.db import models

class ArticleBase(models.Model):
    title = models.CharField()
    author = models.CharField()
    # Store the actual class name.
    class_name = models.CharField()

    # Define save to make sure class_name is set.
    def save(self, *args, **kwargs):
        self.class_name = self.__class__.__name__
        super(ArticleBase, self).save(*args, **kwargs)

    # Multi-table inheritance defines an attribute to fetch the child
    # from a parent instance given the lower case subclass name.
    def get_child(self):
        return getattr(self, self.class_name.lower())

    # If indeed you really need the class.
    def get_child_class(self):
        return self.get_child().__class__

    # Check the type against a subclass name or a subclass.
    # For instance, 'if article.child_is(News):'
    # or 'if article.child_is("News"):'.
    def child_is(self, cls):
        if isinstance(cls, basestring):
            return cls.lower() == self.class_name.lower()
        else:
            return self.get_child_class()  == cls

class Review(ArticleBase):
    rating = models.IntegerField()

class News(ArticleBase):
    source = models.CharField()

. , , . contenttty Contrib , , , , .

ArticleBase :

def __unicode__(self)
    return self.get_child().__unicode__()

, __unicode__ __unicode__ ArticleBase (, ) . , (, ArticleBase ).

:

, , , . , , .

+1

ArticleBase. - - .

. .

80% , .

" " , . , .

, , " ". , - , . , . HTML- , . , .

class Review(ArticleBase):
    rating = models.IntegerField()
    def summary( self ):
        return '<span class="title">%s</span><span class="author">%s</span><span class="rating">%s</span>' %  ( self.title, self.author, self.rating )

News summary.

, .

+1

, , article_type. , .

, . .

0
0

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


All Articles