如何正确编写模型默认函数?
我有一个TestDefalt
模型及其默认功能:
def genefunc(instance, detail):
str = instance.name + "/abc/"
return str
class TestDefalt(models.Model):
name = models.CharField(max_length=11)
detail = models.CharField(default=genefunc, max_length=11)
在我的序列化器和视图中:
# serializer
class TestDefaultSerializer(ModelSerializer):
class Meta:
model = TestDefalt
fields = "__all__"
# view
class TestDCreateAPIView(CreateAPIView):
serializer_class = TestDefaultSerializer
permission_classes = []
queryset = TestDefalt.objects.all()
当我访问TestDCreateAPIView
时,我得到了以下错误:
TypeError at /test04/
Got a `TypeError` when calling `TestDefalt.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `TestDefalt.objects.create()`. You may need to make the field read-only, or override the TestDefaultSerializer.create() method to handle this correctly.
...
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/models/fields/__init__.py", line 782, in get_default
return self._get_default()
TypeError: genefunc() missing 2 required positional arguments: 'instance' and 'detail'
答案 0 :(得分:1)
如果某个字段default
的值是可调用的,则无需任何参数即可调用它,因此您的解决方案无法正常工作。这里适当的解决方案是覆盖save()
方法:
class TestDefalt(models.Model):
name = models.CharField(max_length=11)
detail = models.CharField(default='', max_length=11)
def save(self, *args, **kw):
if not self.pk and not self.detail:
self.detail = self.name + "whatever"
return super(TestDefalt).save(*args, **kw)
请注意,如果len(self.name) == 11
,len(self.name + "something")
将是> 11,所以你可能想为maxlength
设置更大的detail
。