如何在Django模型中将默认字段值设置为其他字段的值?

Joe*_*oel 8 django django-models

如果我在django中有以下型号;

class MyModel(models.Model):  
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100,default=name)
Run Code Online (Sandbox Code Playgroud)

如何使fullname字段默认为name?就像现在一样,fullname默认为CharField名称的字符串表示形式.

例:

new MyModel(name='joel')
Run Code Online (Sandbox Code Playgroud)

会产生'joel'作为名字和全名,而

new MyModel(name='joel',fullname='joel karlsson')
Run Code Online (Sandbox Code Playgroud)

会产生不同的名称和全名.

Dom*_*ger 7

我想知道你是否最好通过模型上的方法做到这一点:

class MyModel(models.Model):  
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100)

    def display_name(self):
        if self.fullname:
            return self.fullname
        return self.name
Run Code Online (Sandbox Code Playgroud)

也许,而不是display_name这应该是你的__unicode__方法.

如果你真的想做你所问过的事情,那么你不能使用default- 使用clean你的表格上的方法(或你的模型,如果你使用新的模型验证(从Django 1.2开始提供) ).

像这样的东西(用于模型验证):

class MyModel(models.Model):
    name = models.CharField(max_length=50)
    fullname = models.CharField(max_length=100,default=name)

    def clean(self):
      self.fullname=name
Run Code Online (Sandbox Code Playgroud)

或者像这样(用于表单验证):

class MyModelForm(ModelForm):
    class Meta:
       model = MyModel

    def clean(self):
        cleaned_data = self.cleaned_data
        cleaned_data['fullname'] = cleaned_data['name']
        return cleaned_data
Run Code Online (Sandbox Code Playgroud)


Bab*_*yan 5

如何使用默认值进行迁移,然后将自定义数据迁移添加到迁移文件中?这是一个完整的迁移文件示例:

from datetime import timedelta

from django.db import migrations, models
import django.utils.timezone


# noinspection PyUnusedLocal
def set_free_credits_added_on(apps, schema_editor):
    # noinspection PyPep8Naming
    UserProfile = apps.get_model('core', 'UserProfile')
    for user_profile in UserProfile.objects.all():
        user_profile.free_credits_added_on = user_profile.next_billing - timedelta(days=30)
        user_profile.save()


# noinspection PyUnusedLocal
def do_nothing(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('core', '0078_auto_20171104_0659'),
    ]

    operations = [
        migrations.AddField(
            model_name='userprofile',
            name='free_credits_added_on',
            # This default value is overridden in the following data migration code
            field=models.DateTimeField(
                auto_now_add=True,
                default=django.utils.timezone.now,
                verbose_name='Free Credits Added On'
            ),
            preserve_default=False,
        ),
        migrations.RunPython(code=set_free_credits_added_on, reverse_code=do_nothing),
    ]
Run Code Online (Sandbox Code Playgroud)

此处该free_credits_added_on字段设置为现有next_billing字段之前 30 天。