簡體   English   中英

帶有附加模型字段的 Django 代理模型?

[英]Django proxy model with additional model fields?

我正在編寫一個像報紙一樣工作的 Django 應用程序。 我有文章,然后我有在某些上下文中出現的那些文章的自定義版本。 因此,我可以在報紙的頭版上有一篇文章的版本,該版本具有文章原始標題的較短版本。 所以我有:

class Article(models.Model):
    """ A newspaper article with lots of fields """
    title = models.CharField(max_length=255)
    content = models.CharField(max_length=255)

    # Lots of fields...

我想要一個CustomArticlè object that is a proxy for the Articlè CustomArticlè object that is a proxy for the ,但有一個可選的替代標題:

class CustomArticle(Article):
    """ An alternate version of a article """
    alternate_title = models.CharField(max_length=255)

    @property
    def title(self):
        """ use the alternate title if there is one """
        if self.custom_title:
            return self.alternate_title
        else:
            return self.title
            
    class Meta:
        proxy = True
    
    # Other fields and methods

不幸的是,我無法向代理添加新字段:

>>> TypeError: Abstract base class containing model fields not permitted for proxy model 'CustomArticle'

所以,我可以做這樣的事情:

class CustomArticle(models.Model):
    # Other methods...
    
    original = models.ForeignKey('Article')

    def __getattr__(self, name):
        if hasattr(self.original):
            return getattr(self.original, name)
        else:
            return super(self, CustomArticle).__getattr__(name)

但不幸的是, __getattr__似乎不適用於 Django 模型。 Article類中的字段可能會更改,因此為 CustomArticle 中的每個字段都創建一個@property方法是不切實際的。 這樣做的正確方法是什么?

看起來這可能適用於__getattr__

def __getattr__(self, key):

    if key not in ('original', '_ original_cache'):
        return getattr(self.original, key)      
    raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, key))

讓 CustomArticle 成為 Article 的子類怎么樣? Django 模型確實支持繼承! 看看: https : //docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance

嘗試這樣的事情:

class CustomArticle(models.Model):
    # Other methods...

    original = models.ForeignKey('Article')

    def __getattr__(self, name):
        return getattr(self.original, name)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM