开发者

Instantiate django model from parent data

Is it possible to instantiate a subclassed model from its parent?

class Object1(models.Model):
  field1a = models.CharField()
  field1b = models.CharField()
  feild1c = models.ForeignKey(Object4)      

class Object2(Object1):
  field3 = models.CharField()

class Object3(Object1):
  field3 = models.CharField()

class Object4(models.Model):
  field4 = models.CharField()

What I want to do is create the base class first and then based on some rule instantiate one of the subclasses but using the already created base class.

Something like:

obj4 = Object4(field4='d')
obj1 = Object1(field1a='a', field1b='b', field1c=obj4)
if somerule:
  obj2 = Object2(object1_ptr=obj1, field2='2')
else:
  obj3 = Object3(object1_ptr=obj1, field3='3')

I don't want to repeat t开发者_JAVA百科he Object1 fields in the if/else clauses. Is it possible to accomplish this? When I try this I get a Foreign key error; Cannot add or update a child row: A foreign key constraint fails


I recommend doing something like this:

attr = dict(field1a='a', field1b='b', field1c=obj4)
obj1 = Object1(**attr)
if somerule:
    attr["field2"] = 2
    obj2 = Object2(**attr)
else:
    attr["field3"]='3'
    obj3 = Object3(**attr)

Be aware that the dictionary attr changes in place.


What you're doing is almost correct, but if you want to copy it you will have to remove the primary key.

So... this should fix it: del obj2.id Do note however that if some other model references your model with a foreign key that it references obj1, not obj2. And obj1 will, ofcourse, still exist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜