【问题标题】:Separate Django model field to another fields将 Django 模型字段与另一个字段分开
【发布时间】:2021-09-16 02:00:56
【问题描述】:

我有一个名为 fullname 的字段,其中包含如下数据:

first_name:Gholi;last_name:Sezavar Poor Asl Esfahani

我想将其分隔为两个单独的字段名称 first_name 和 last_name。

我的 models.py 是:

from django.db import models

class Person(models.Model):

    fullname = models.CharField(max_length=250, null=True)
    information = models.CharField(max_length=350, null=True)
    first_name = models.CharField(max_length=30, null=True)
    last_name = models.CharField(max_length=50, null=True)
    id_code = models.CharField(max_length=10, null=True)
    born_in = models.CharField(max_length=30, null=True)
    birth_year = models.PositiveIntegerField(null=True)

我想为它进行自定义迁移并使用注释方法。 我该怎么做???

编辑:

我想在自定义迁移中执行此操作并使用注释方法,就像我现在所做的那样,但现在使用我的代码它只是将名字和姓氏存储在 first_name 字段中:

def organize_person_schema(apps, schema_editor):
    # Person = apps.get_model('people', 'Person')
    Person.objects.annotate(
        first_name_change=Replace(
            F('fullname'), text=Value("first_name:"),
            replacement=Value(''),
            output_field=CharField()
        )
    ).update(first_name=F('first_name_change'))
    Person.objects.annotate(
        last_name_change=Replace(
            F('first_name'), text=Value(";last_name:"),
            replacement=Value(' '),
            output_field=CharField()
        )
    ).update(first_name=F('last_name_change'))
    Person.objects.annotate(
        last_name_last=Concat(
            F('first_name'), Value(""),
            output_field=CharField()
        )
    ).update(last_name=F('last_name_last'))

【问题讨论】:

    标签: django orm model django-orm


    【解决方案1】:

    你可以有一个自定义的保存方法来做一些更新:

    from django.db import models
    
    class Person(models.Model):
    
        fullname = models.CharField(max_length=250, null=True)
        information = models.CharField(max_length=350, null=True)
        first_name = models.CharField(max_length=30, null=True)
        last_name = models.CharField(max_length=50, null=True)
        id_code = models.CharField(max_length=10, null=True)
        born_in = models.CharField(max_length=30, null=True)
        birth_year = models.PositiveIntegerField(null=True)
    
        def save(self, *args, **kwargs):
            if not self.pk:
                # logic to separate full name into first and last
                # Split by (";")
                first_name, last_name = self.fullname.split(";")
                self.first_name = first_name.split(":")[1]
                self.last_name = last_name.split(":")[1]
                super(Person, self).save(*args, **kwargs)            
    

    【讨论】:

      猜你喜欢
      • 2021-10-05
      • 2019-03-11
      • 2017-01-31
      • 2015-09-26
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      相关资源
      最近更新 更多