Django fixtures使用默认值保存

2024-03-28 15:03:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是django1.7,我的设备有问题。在

我希望Django使用默认值或使用save()方法创建未指定的值。在

以下是我当前的对象:

# File: uuidable.py
import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _


class Uuidable(models.Model):
    uuid = models.CharField(_('uuid'), blank=True,
                            null=False, unique=True,
                            max_length=64, default=uuid.uuid4())  # Tried here

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.uuid = uuid.uuid4()  # Tried here also
        super().save(*args, **kwargs)

# File: timestampable.py
from django.db import models
from django.utils.translation import ugettext_lazy as _


class Timestampable(models.Model):
    created_at = models.DateTimeField(_('created at'), auto_now_add=True)
    updated_at = models.DateTimeField(_('updated at'), auto_now=True)

    class Meta:
        abstract = True

# File: post.py
from project.lib.models.timestampable import Timestampable
from project.lib.models.uuidable import Uuidable

class Post(Timestampable, Uuidable):
    title = models.CharField(_('title'), max_length=250, blank=False)
    content = models.TextField(_('content'))

    def __str__(self):
        return self.title

如您所见,当我生成一个新的Post()时,created_atupdated_at和{}值会自动在save()上创建。但是当我使用fixture时,我得到了以下错误:

^{pr2}$

如果我在fixture文件中指定一个uuid,那么我在created_at上得到一个错误,然后在updated_at上得到一个错误。所以我必须指定每个字段的内容,即使我希望它是“自动”的。在

documentation(为什么这是在django管理文档中?!),我知道save()方法没有被调用,所以这就是我放入save()方法的所有内容都不起作用的原因。但是defaultauto_now*特性不应该启用/使用吗?在

When fixture files are processed, the data is saved to the database as is. Model defined save() methods are not called, and any pre_save or post_save signals will be called with raw=True since the instance only contains attributes that are local to the model. You may, for example, want to disable handlers that access related fields that aren’t present during fixture loading and would otherwise raise an exception

有没有一种方法可以“强制”Django自动地对fixture使用defaultauto_now*特性?我使用manage.py syncdb创建所有表等

我已经搜索了谷歌和堆栈溢出,但似乎找不到正确的搜索关键字。在

UPDATE-1:下面的google group discussion表示对象是以raw模式保存的,这意味着auto_now*特性没有被考虑在内。我仍在寻找是否有一种方法将一些模型函数挂接到Django fixture保存中。在


Tags: django方法frompyimportselftrueauto
3条回答

Automatically loading initial data fixtures is deprecated in Django 1.7。一个解决方案是通过你提到的信号。 另一个我更喜欢的方法是创建一个python脚本,在其中创建所有需要的数据,并在shell中执行:

python manage.py shell < create_initial_data.py

我认为问题是当你把default=uuid.uuid4()放进去的时候。括号太多了,因为它们暗示您将uuid.uuid4()的结果传递给默认参数,而不是函数本身,因此您应该将default=uuid.uuid4放入。在

解决方案是使用django信号:

import uuid
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_save
from django.dispatch import receiver

class Uuidable(models.Model):
    uuid = models.CharField(_('uuid'), blank=True,
                            null=False, unique=True,
                            max_length=64, default=uuid.uuid4())

    class Meta:
        abstract = True

    @receiver(pre_save)
    def set_uuid_on_save(sender, instance, *args, **kwargs):
        if instance.pk is None:
            instance.uuid = uuid.uuid4()

这样,无论以何种方式创建模型(通过shell、fixture等等),都会填充模型/数据。在

相关问题 更多 >