Friday, April 29, 2011

Re: Using composition in Django

Thanks for the clarification, I put in the ForeignKey in employee class and is working.
Regards!

2011/4/27 Tom Evans <tevans.uk@googlemail.com>
On Sun, Apr 17, 2011 at 9:21 PM, W Craig Trader <craig.trader@gmail.com> wrote:
> If your goal is to have an employee object that has direct access to all of
> its related person object, and whose only new data field is a reference to
> an address object, then you should change the Employee model to this:
>
> class Address(models.Model):
>    pass
>
> class Person(models.Model):
>    name = models.CharField(max_length=50)
>    date_inclusion = models.DateField()
>
> class Employee(models.Model):
>    person = models.OneToOneField(Person)
>    address = models.ForeignKey(Address)
>

Just to point out, this is MTI reinvented, without any of the Django
syntactic magic sprinkled on top. It is exactly equivalent to this:

class Address(models.Model):
   pass

class Person(models.Model):
   name = models.CharField(max_length=50)
   date_inclusion = models.DateField()

class Employee(Person):
   address = models.ForeignKey(Address)

"""
The second type of model inheritance supported by Django is when each
model in the hierarchy is a model all by itself. Each model
corresponds to its own database table and can be queried and created
individually. The inheritance relationship introduces links between
the child model and each of its parents (via an automatically-created
OneToOneField).
Cheers

Tom

--
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.


--
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.

No comments:

Post a Comment