Creating and saving non-empty Django model instance as part of subclass instance -


i experiencing strange behavior inconsistent django documentation while creating , saving (inserting db) model instance. i've run out of ideas possible reason , grateful suggestions why django fails save fields in these cases.

this class using:

class person(models.model):     user = models.foreignkey(user)     phone_number = models.charfield(max_length=20, blank=true)     address     = models.charfield(max_length=200, blank=true) 

and here's code does't work, few cases:

# first case new_person = person() new_person.user = request.user new_person.phone_number = '111111' new_person.save(force_insert=true)  # second 1 new_person = person(user=request.user, phone_number='111111') new_person.save(force_insert=true)  # third 1  new_person = person.objects.create(user=request.user, phone_number='111111') 

basing on official django docs in case django should create object , insert db.

in fact object created (and relevant fields set), row inserted db has id , user_id fields filled correctly while phone_number field set, remains blank.

there is, however, no problem access , update fields of existing (saved earlier) objects.

removing blank=true person class declaration (with proper table alteration) does't change anything.

edit: problem turned out more sophisticated. full description , solution in own answer beneath

ok, found explanation....

it has inheritance, namely further in code wanted create instance of person's subclass. there class:

class person(models.model):     user = models.foreignkey(user)     phone_number = models.charfield(max_length=20, blank=true)     address     = models.charfield(max_length=200, blank=true)  class connectedperson(person):     connection = models.foreignkey(anotherclass)     # etc.. 

and after creating instance of person, intending extend connectedperson made such code:

#creating instance of person: person = person(user=request.user, phone_number='111111') person.save(force_insert=true)  c_person = connectedperson(id=person.id, connection=instance_of_another_c) 

and using connectedperson(id=person.id) in fact killing created person instance overwritting in db.


so not experienced in managing inheriting instances: if need use earlier created super class instance part of subclass instance way:

#creating person not saving person = person(user=request.user, phone_number='111111')  ###### #later ######   #creating subclass instance , saving c_person = connectedperson(user=request.user, connection=instance_of_another_c) c_person.save()  #saving super class instance part of subclass instance person.pk = super(connectedperson, c_person).pk person.save() 

Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -