让我们考虑一下我有很多人拥有一些衬衫的情况:
class Person(models.Model):
name = models.CharField()
class Shirt(models.Model):
description = models.CharField()
owner = models.ForeignKey(Person)
我在他们的一件衬衫上拍摄了他们的肖像照片:
class Photo(models.Model):
person = models.ForeignKey(Person)
shirt = models.ForeignKey(Shirt)
在模板中我使用
之类的东西{{ the_photo.shirt.description }}
和
{% for shirt in the_person.shirt_set.all %}
{{ shirt.description }}
{% endfor %}
我也有表格让我从模特的库存中挑选一件衬衫照片。
现在,扭曲!我还可以拍一张没有衬衫的照片!因此,除了他们可能拥有的任何衬衫之外,我希望the_person.shirt_set
还包含description='topless'
条目。我宁愿不为每个人存储额外的'topless'
衬衫,也不想修改每个表格和列表以添加此选项。
我想到了创建一个Topless
类:
class Topless(Shirt):
def __init__(self, *args, **kwargs):
super(Topless, self).__init__(*args, **kwargs)
self.description = 'Topless'
并将其添加到列表中:
class Person(models.Model):
name = models.CharField()
def shirts(self):
l = list(Shirt.objects.filter(owner=self))
l.insert(0, Topless())
return l
(当然,在模板中从the_person.shirt_set
切换到the_person.shirts
),但由于id为None(或0),因此the_photo.shirt
变得丑陋,看起来它会需要一堆丑陋的黑客可以容纳它。
但也许我做错了?有任何想法吗?什么是最优雅和pythonic的方式呢?