Opened 10 years ago

Closed 10 years ago

#23465 closed Bug (duplicate)

Inheritance destroying data in original model

Reported by: leandropls Owned by: nobody
Component: Database layer (models, ORM) Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by leandropls)

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 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. But as I inherit from User and set its OneToOneField to an existing instance of the user, the specified existing instance gets destroyed. The expected result was that django simply made the association.

Change History (5)

comment:1 by sargikk, 10 years ago

Another example with same problem when OneToOneField related to the inherited model.

from django.contrib.auth.models import User
(...)
class PersonUser(User):
    name = models.CharField(max_length=255)
    surname = models.CharField(max_length=255)

class OnetoOneToUser(Model):
    user = models.OneToOneField(Parent, blank=True, null=True)
    info = models.CharField(max_length=255, default='some parent info')
>>> person_user = PersonUser(username = 'first_user', name='1', surname='1')
>>> person_user.save()
>>> User.objects.all()
[<User: first_user>]
>>> one_to_one = OnetoOneToUser(user=person_user)
>>> one_to_one.save()
>>> person_user_2 = PersonUser(username = 'second_user', name='1', surname='1')
>>> person_user_2.save()
>>> User.objects.all() 
[<User: second_user>]
Last edited 10 years ago by sargikk (previous) (diff)

in reply to:  1 comment:2 by leandropls, 10 years ago

Replying to sargikk:

What's the state of User.objects.all() after one_to_one.save()?

comment:3 by leandropls, 10 years ago

Description: modified (diff)

comment:4 by Aymeric Augustin, 10 years ago

This appears to be the same problem as #7623.

comment:5 by Tim Graham, 10 years ago

Resolution: duplicate
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top