我想制作下一个模型架构:
class Place(models.Model):
"""
This is base class for all places like shops, trc, restaurants, etc.
"""
name = models.CharField(_('Place name'), max_length=255, unique=True, null=True, blank=True)
partner = models.ForeignKey('Partner', verbose_name=_('Partner'), related_name='places')
...
# next line causes errors
trc = models.ForeignKey('Trc', related_name='places', null=True, blank=True)
class Trc(Place): # Trc is equal to Mall - place which contains shops, cafes, cinemas
...
class Shop(Place):
...
class Restaurant(Place):
...
在Place模型中添加'trc'字段将使查询更好和通用,但是当我尝试在db中创建这样的表时,我收到以下错误:
CommandError: One or more models did not validate:
partner.trc: Accessor for field 'place_ptr' clashes with field 'Place.trc'. Add a related_name argument to the definition for 'place_ptr'.
partner.trc: Reverse query name for field 'place_ptr' clashes with field 'Place.trc'. Add a related_name argument to the definition for 'place_ptr'.
玩相关名称没有帮助......我真的不想在商店和餐厅中移动'trc'字段。谢谢
答案 0 :(得分:1)
改为
class Place(models.Model):
name = models.CharField(_('Place name'), max_length=255, unique=True, null=True, blank=True)
partner = models.ForeignKey('Partner', verbose_name=_('Partner'), related_name='places')
...
# next line causes errors
#trc = models.ForeignKey('Trc', related_name='places', null=True, blank=True)
class Trc(Place): # Trc is equal to Mall - place which contains shops, cafes, cinemas
place = models.ForeignKey(Place, related_name='trc', ...)
等
答案 1 :(得分:1)
无需添加trc
字段,因为它已经存在。查看django docs on multi-table inheritance中非常相似的示例:
如果您的
Place
也是Restaurant
,,您可以从Place
对象转到 { {1}} 通过使用模型名称的小写版本:
Restaurant
但是,如果上例中的
p = Place.objects.get(id=12) # If p is a Restaurant object, this will give the child class: p.restaurant <Restaurant: ...>
不是p
(原来是Restaurant
直接创建为Place
对象或者是其他对象的父对象 (),提到p.restaurant would
提出一个Restaurant.DoesNotExist
例外。