我正在使用 Django 1.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()
, the created_at
, updated_at
and uuid
值自动创建于save()
。但是当我使用固定装置时,我收到以下错误:
[...]initial_data.yaml': Could not load post.Post(pk=None): UNIQUE constraint failed: post_post.uuid
如果我指定一个uuid
在我的装置文件中,然后我收到错误created_at
然后继续updated_at
。所以我必须指定每个字段的内容,即使我希望它是“自动的”。
来自文档 https://docs.djangoproject.com/en/1.7/ref/django-admin/(为什么这是在 django 中admin文档?!),我知道save()
方法没有被调用,所以这就是为什么我将所有内容放入save()
方法不起作用。但不应该是default
or auto_now*
启用/使用功能?
处理夹具文件时,数据按原样保存到数据库中。不会调用模型定义的 save() 方法,并且将使用 raw=True 调用任何 pre_save 或 post_save 信号,因为实例仅包含模型本地的属性。例如,您可能想要禁用访问夹具加载期间不存在的相关字段的处理程序,否则会引发异常
有没有办法“强制”Django 自动使用default
or auto_now*
灯具的特点 ?我在用着manage.py syncdb
创建所有表等。
我在谷歌和堆栈溢出上进行了搜索,但似乎找不到正确的搜索关键字。
UPDATE-1: 下列谷歌小组讨论 https://groups.google.com/forum/#!topic/django-users/Zfqx-kEE2uY说对象保存在raw
模式,意味着auto_now*
不考虑特征。我仍在寻找是否有办法将某些模型函数挂接到 Django 固定装置保存中。