如何使用Django创建子类?

时间:2019-05-13 14:45:40

标签: python django python-3.x postgresql django-models

您好,我在PostgreSQL数据库中使用django,在我的数据库中,我有5列,其中一列称为:“ data”,数据中包含:

|data |
|{"name":"Peter","city":"New York"}|
|{"name":"Denis","city":"Paris"}|
|{"name":"Jennifer","city":"San Francisco"}|
|{"name":"Kim","city":"Berlin"}|

我想提取此列并以dataExtract的名称创建一个子表,例如:

|name|city|
|Peter|New York|
|Denis|Paris|
|Jennifer|San Francisco|
|Kim|Berlin|

能帮我吗?

非常感谢您!

1 个答案:

答案 0 :(得分:0)

创建新模型:

class DataExtract(Base):
    main = models.OneToOneField(
        MainModel,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    name = models.CharField(default=None, max_length=400, blank=True)
    city = models.CharField(default=None, max_length=400, blank=True)

要使用MainModel表中的现有数据填充ExtractData表,请仅使用此代码一次:

for main in MainModel.object.all():
    ExtractData.create(name=main.data__name,city=main.data__city)

在最初填充DataExtract表之后,现在您必须使用信号在每次插入MainModel表之后插入DataExtract表,如下所示:

class DataExtract(Base):
    ......
    ......

    @receiver(post_save, sender=MainModel)
        def create_data_extract(sender, instance, created, **kwargs):
            # you have to check here for duplicate, 
            # if there is no duplicate, create it.
            # if there is duplicate update that
            ExtractData.create(name=instance.data__name,city=instance.data__city)