简体   繁体   English

如何将默认数据添加到django model

[英]How to add default data to django model

I have a web app with the following model我有一个 web 应用程序,其中包含以下 model

class Records(models.Model):
    alias = models.CharField(max_length=17, unique=True)
    status = models.BooleanField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.alias

    def list_data(self):
        return [self.alias, self.status, self.created_at, self.updated_at]

I want some default data to be populated into this model on creation.我希望在创建时将一些默认数据填充到此 model 中。 I went through the documentation and this StackOverflow question for doing the same.我浏览了文档和这个StackOverflow 问题来做同样的事情。

I first ran this command to create a migrations file (0001_initial.py)我首先运行这个命令来创建一个迁移文件(0001_initial.py)

python manage.py makemigrations --empty main_app

I then edited the migrations file as follows然后我按如下方式编辑了迁移文件

0001_initial.py 0001_initial.py

# Generated by Django 4.0.3 on 2022-04-23 05:57

from django.db import migrations

def add_initial_data(apps, schema_editor):

    Records = apps.get_model('main_app', 'Records')
    for record in Records.objects.all():
        record.alias = f'ACCORD1'
        record.status = True
        record.save()
        
        for i in range(2,6):
            record.alias = f'ACCORD{i}'
            record.status = False
            record.save()

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(add_initial_data)
    ]

When I run the migrations with the following command当我使用以下命令运行迁移时

python manage.py migrate

I get the following error我收到以下错误

LookupError: No installed app with label 'main_app'.

I tried adding the dependency to the migrations file as follows我尝试将依赖项添加到迁移文件中,如下所示

dependencies = [
        ('main_app', '0001_initial')
    ]

But this gives me the following error但这给了我以下错误

django.db.migrations.exceptions.CircularDependencyError: main_app.0001_initial

I am not sure what I am doing wrong.我不确定我做错了什么。

CircularDependencyError循环依赖错误

The circular dependency error is encountered when a file being called is associated with a dependency, which has the file being called as its dependency.当被调用的文件与依赖项相关联时遇到循环依赖项错误,该依赖项将被调用的文件作为其依赖项。

In the file main_app/001_initial.py , you added the dependency main_app/001_initial.py by adding the line:在文件main_app/001_initial.py中,您通过添加以下行添加了依赖main_app/001_initial.py

dependencies = [
    ('main_app', '0001_initial')
]

On migration, the confusion arises whether to import the file main_app/001_initial.py or the dependency main_app/001_initial.py whose dependency is the file main_app/001_initial.py .在迁移时,会出现混淆是导入文件main_app/001_initial.py还是依赖文件main_app/001_initial.py其依赖文件main_app/001_initial.py Hence, creating a circular dependency pattern.因此,创建了一个循环依赖模式。

Adding default values.添加默认值。

Adding multiple rows of data from migration file is not part of a good coding paradigm.从迁移文件中添加多行数据不是一个好的编码范例的一部分。 You would want to use a different method.你会想要使用不同的方法。

Add default values to model itself.将默认值添加到 model 本身。

These values will only help to add default values when saving one instance at a time.这些值只会在一次保存一个实例时帮助添加默认值。

class Records(models.Model):
    alias = models.CharField(max_length=17, unique=True, default="ACCORD")
    status = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return self.alias

Now there are multiple ways to populate the table with data.现在有多种方法可以用数据填充表。

  1. Link the django app to the database with data rows already in place.将 django 应用程序链接到数据库,其中数据行已经到位。
  2. Add a serializer function BulkCreate to add values in bulk.添加序列化程序 function BulkCreate 以批量添加值。
  3. Use the command line shell manually to create model instances that would populate the database table.手动使用命令行 shell 创建将填充数据库表的 model 个实例。 You can read about using python manage.py shell and python manage.py shellplus .您可以阅读有关使用python manage.py shellpython manage.py shellplus
  4. Use a python script to add the data by creating model instances with the desired values.使用 python 脚本通过创建具有所需值的 model 个实例来添加数据。

Another tip另一个提示

Instead of using a list_data function in models.py , using a django serializer would serve more functionality and is a better way to code.而不是在models.py中使用list_data function,使用 django 序列化程序将提供更多功能,并且是一种更好的编码方式。

The idea is to keep models.py as clean as possible with only the attribute definitions there.这个想法是让models.py尽可能干净,只有属性定义在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM