在django中将子类模型实例转换为另一个子类模型实例?

2024-05-29

我有一个 ModelBase、ModelA、ModelB。

我想将模型实例更改为模型实例。 (我可以处理他们的属性差异)

我看过相关问题,但对我来说不太有用。

如何从现有的基本模型实例创建继承的 django 模型实例? https://stackoverflow.com/questions/14034486/how-can-i-create-an-inherited-django-model-instance-from-an-existing-base-model
更改 django 模型上的子级 https://stackoverflow.com/questions/19967714/change-class-of-child-on-django-models

  • EDIT

当您有场所 - 餐厅/酒吧关系时,
我觉得能够把餐厅改成酒吧是相当合理的。


我必须处理同样的问题,yuvi 和 arctelix 的答案都不适合我。 yuvi 解决方案给出错误,arctelix 解决方案使用新的 pk 创建新对象。

这里的目标是更改子类模型,同时保持原始超类与旧 pk 一样。

First:删除old子类并保留超类。检查Django 文档 https://docs.djangoproject.com/en/1.10/ref/models/instances/#django.db.models.Model.delete.

Second:添加新的子类及其字段并将超类传递给它。 查看this q https://stackoverflow.com/questions/4064808/django-model-inheritance-create-sub-instance-of-existing-instance-downcast

Example:地点可以是餐厅或咖啡馆,并且您想将餐厅地点更改为咖啡馆;如下:

class Place(models.Model):
            name = models.CharField(max_length=50)
            address = models.CharField(max_length=80)

class Caffe(Place):
    serves_hot_dogs = models.BooleanField(default=False)
    serves_pizza = models.BooleanField(default=False)

class Restaurant(Place):
    serves_tea = models.BooleanField(default=False)
    serves_coffee = models.BooleanField(default=False)

# get the objecte to be changed
rest = Restaurant.objects.get(pk=1) #arbitrary number
#delete the subclass while keeping the parent
rest.delete(keep_parents=True)

place = Place.objects.get(pk=1) # the primary key must be the same as the deleted restaurant

# Create a caffe and pass the original place
caffee = Caffe(place_ptr_id=place.pk) #this will empty the parent field

#update parent fields
caffee.__dict__.update(place.__dict__)

#add other field
........

#save the caffe
caffee.save()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在django中将子类模型实例转换为另一个子类模型实例? 的相关文章

随机推荐