从Django中的基本模型实例返回代理模型实例的正确方法? [英] Right way to return proxy model instance from a base model instance in Django?
问题描述
class Animal(models.Model):
type = models.CharField max_length = 255)
class Dog(Animal):
def make_sound(self):
printWoof!
class Meta:
proxy = True
class Cat(Animal):
def make_sound(self):
print喵!
class Meta:
proxy = True
让我们说要做:
animals = Animal.objects.all()
动物动物:
animal.make_sound )
我想收回一系列Woofs和Meows。显然,我可以在原始模型中定义一个基于animal_type的一个make_sound,但是每当我添加一个新的动物类型(想象它们在不同的应用程序中)时,我必须进入并编辑make_sound函数。我宁愿只是定义代理模型,并让他们自己定义行为。从我可以看出来,没有办法返回混合的Cat或Dog实例,但是我想也许我可以在主类上定义一个返回一个猫或狗模型的get_proxy_model方法。
当然你可以这样做,并传递一些像主键,然后只是做Cat.objects.get(pk = pass_in_primary_key)。但这意味着对已经拥有的数据进行额外的查询,这似乎是多余的。有没有办法有效地将动物变成猫或狗的实例?什么是正确的方法来做我想要实现的?
你可以使用描述的方法使Django模型多态href =http://groups.google.com/group/django-developers/msg/b567b75fe61d5044 =nofollow noreferrer> here 。该代码处于开发的早期阶段,我相信,但值得调查。
Say I have models:
class Animal(models.Model):
type = models.CharField(max_length=255)
class Dog(Animal):
def make_sound(self):
print "Woof!"
class Meta:
proxy = True
class Cat(Animal):
def make_sound(self):
print "Meow!"
class Meta:
proxy = True
Let's say I want to do:
animals = Animal.objects.all()
for animal in animals:
animal.make_sound()
I want to get back a series of Woofs and Meows. Clearly, I could just define a make_sound in the original model that forks based on animal_type, but then every time I add a new animal type (imagine they're in different apps), I'd have to go in and edit that make_sound function. I'd rather just define proxy models and have them define the behavior themselves. From what I can tell, there's no way of returning mixed Cat or Dog instances, but I figured maybe I could define a "get_proxy_model" method on the main class that returns a cat or a dog model.
Surely you could do this, and pass something like the primary key and then just do Cat.objects.get(pk = passed_in_primary_key). But that'd mean doing an extra query for data you already have which seems redundant. Is there any way to turn an animal into a cat or a dog instance in an efficient way? What's the right way to do what I want to achieve?
You can perhaps make Django models polymorphic using the approach described here. That code is in early stages of development, I believe, but worth investigating.
这篇关于从Django中的基本模型实例返回代理模型实例的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!