1.你并没有真正获得任何Python继承,也就是说你不能从模型类继承/覆盖方法或属性Place
在你的班级里Restaurant
:
例如:
class Place(models.Model):
name = models.CharField(max_length=50)
def get_x(self):
return 'x'
class Restaurant(models.Model):
place = models.OneToOneField(Place)
serves_pizza = models.BooleanField()
a_restaurant = Restaurant()
a_restaurant.get_x() # -> wouldn't work
这意味着要获得name
一家你做不到的餐厅a_restaurant.name
,您需要点击以下链接:a_restaurant.place.name
另请注意,查询时Place
与相关的对象Restaurant
.
a_restaurant.save()
Place.objects.get(pk=a_restaurant.pk) # won't work
你必须写:
a_restaurant.save()
Place.objects.get(restaurant__pk=a_restaurant.pk)
2 and 3。几乎是一样的。你确实可以通过这些获得真正的Python继承。
a_restaurant = Restaurant()
a_restaurant.get_x() # would actually work and print 'x'
你的模特班Restaurant
继承了一切Place
:模型字段、普通实例/类属性、管理器、方法...您还可以覆盖几乎所有内容:您无法覆盖字段属性,这是不受支持的。
现在您可以直接从父模型获取字段的值:a_restaurant.name
因为它们是遗传的。
由于通过这些实施Restaurant
is a also Place
你可以查询Place
对象与Restaurant
data:
a_restaurant.save()
the_place = Place.objects.get(pk=a_restaurant.pk)
# ^ this works now and returns the equivalent `Place` instance.
the_same_restaurant = the_place.restaurant
The 不同之处如果您为该字段指定不同的名称,则在 2 和 3 之间更容易查看:
class Place(models.Model):
name = models.CharField(max_length=50)
class Restaurant(Place):
where = models.OneToOneField(Place, parent_link=True)
serves_pizza = models.BooleanField()
工作原理完全相同,但要获取 a 的父位置Restaurant
属性名称是where
:
the_place = a_restaurant.where
with 2本来可以:
the_place = a_restaurant.place_ptr
这些意味着place = models.OneToOneField(Place, parent_link=True)
只会更改父模型实例的链接名称。默认名称是'{lowercase_model_name}_ptr'
.
最后一个例子:
With 1:
place1 = Place.objects.create(name='place_1')
place2 = Place.objects.create(name='place_2')
restaurant1 = Restaurant.objects.create(place=place1, serves_pizza=True)
print Place.objects.all() # prints [place1, place2]
print Restaurant.objects.all() # prints [restaurant1]
With 2-3:
place1 = Place.objects.create(name='place_1')
place2 = Place.objects.create(name='place_2')
restaurant1 = Restaurant.objects.create(name='place_3', serves_pizza=True)
print Place.objects.all() # prints [place1, place2, place3]
print Restaurant.objects.all() # prints [restaurant1]
希望这些有帮助。它长得有点太长了:/