Sunday, October 24, 2010

Re: inheritance of fields and default values from parent model class

pixelcowboy wrote:

> Hi, I would like to create an inheritance relationship, similar to an
> abstract class, where the child class inherits all thefieldsfrom the
> parent class, but also gets its default values from the parent
> instance. So basically Im confused about the concepts, I know an
> abstract class would not have a particular instance, but I would like
> the child class toinheritthefieldsand field values from an actual
> parent instance, but with the capability of overriding them.

I have a related problem. And so did this guy, some years ago:

zeliboba wrote:

> I'd like to have certainfieldsin several models, like alias field in
> this:
>
> class Person(models.Model):
>     name = models.CharField(max_length=255)
>     alias = models.ForeignKey('self', blank=True, null=True)
>
> class Place(models.Model):
>     street = models.CharField(max_length=255)
>     alias = models.ForeignKey('self', blank=True, null=True)
>
> to repeat alias in everymodelis not DRY. also I'd like to have
> Manager returning for example all aliases for all of such models andmodelmethods to manipulate with aliases. so it should be common for
> several models. I see a way to achieve this is toinherit
> models.Model, add necessaryfields/managers/methods to it and theinheritmy models from it, like:
>
> class MyModel(models.Model):
>     alias = models.ForeignKey('self', blank=True, null=True)
>     manager = [my alias manager here]
>     def getAlias:
>           [whatever I need]
>
> class Person(MyModel):
>     name = models.CharField(max_length=255)
>
> class Place(MyModel):
>     street = models.CharField(max_length=255)
>
> my questions are:
> 1. is it the right way to go?
> 2. are there any pitfalls?

What we discovered doing that is we get an extra database table called
_mymodel, and we don't need it.

So then I tried it like this:

class MyModel:
    alias = models.ForeignKey('self', blank=True, null=True)
    manager = [my alias manager here]

class Person(models.Model, MyModel):
    name = models.CharField(max_length=255)

class Place(models.Model, MyModel):
    street = models.CharField(max_length=255)

And now the model can't see the fields 'alias' or 'manager'.

How do I (redundantly!) give the two model records the same
boilerplate fields?

--
Phlip
http://zeekland.zeroplayer.com/

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate