Django proxy model and ForeignKey

前端 未结 6 2059
温柔的废话
温柔的废话 2020-12-05 01:28

How to make entry.category to be instance of CategoryProxy? See code for details:

class Category(models.Model): pass

class Entry(models.Model):
    category         


        
6条回答
  •  有刺的猬
    2020-12-05 01:44

    Adapting Bernd Petersohn's answer slightly, we then have:

    class EntryProxy(Entry):
        @property
        def category(self):
            return CategoryProxy.objects.get(id=self.category_id)
    

    This ought to be more economical with the database. For added improvements you could set a private attribute (self._category) the first time the method is called, then return that all subsequent times.

提交回复
热议问题