Leandro Lima
Leandro Lima

Reputation: 5418

Using Django Multi-table inheritance and OneToOneField

I've created the following model:

school/models.py:

from django.contrib.auth.models import User
(...)
class Parent(User):
    contract = models.ForeignKey(Contract)
    user = models.OneToOneField(User, parent_link = True, related_name = 'school_parent')

Now I'm trying to "promote" a regular django user into a school parent:

>>> from django.contrib.auth.models import User
>>> from school.models import Parent, Contract
>>> u = User(username = 'myuser')
>>> u.save()
>>> User.objects.all()
[<User: myuser>]
>>> c = Contract.objects.get(pk = 1)
>>> p = Parent(user = u, contract = c)
>>> p.save()
>>> User.objects.all()
[<User: >]
>>> 

Apparently, in "Parent" creation, the user "myuser" is being destroyed. Django docs show[1] that you can "attach" one model to other via OneToOneField the way I'm doing. It also says that multi-table inheritance automatically creates a OneToOneField[2].

Is there a way to "promote" a User to Parent in this case? What about demotion?

Reference:

  1. https://docs.djangoproject.com/en/1.6/topics/db/examples/one_to_one/
  2. https://docs.djangoproject.com/en/1.6/topics/db/models/#multi-table-inheritance

Upvotes: 0

Views: 646

Answers (1)

Jonathan
Jonathan

Reputation: 8891

I'm assuming that what you are looking for is handling permissions. A normal django user can do certain things whereas a Parent can do other things. Is that correct?

In that case a better use case would be to use the built-in groups with permissions that django has. You can thus create a group called parents. Which has certain permissions whereas a normal django user can't do those stuff. You can read more about permissions in the docs.

If you are looking for adding more data to the User it would be better to add that to a profile where you have a OneToOneField to the User

Upvotes: 1

Related Questions