从documentation读取自定义字段(在“字段解构”下):
If you haven’t added any extra options on top of the field you inherited from, then there’s no need to write a new deconstruct() method. If, however, you’re changing the arguments passed in __init __() (like we are in HandField), you’ll need to supplement the values being passed.
提供的示例(不包括解构器代码)HandField
是:
from django.db import models
class HandField(models.Field):
description = "A hand of cards (bridge style)"
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 104
super(HandField, self).__init__(*args, **kwargs)
我的问题是:文档中所说的“额外选项”到底是什么?在上面的例子中,究竟是什么使解构主义的创造成为强制性的?调用super(HandField, self).__init__(*args, **kwargs)
与调用从中继承的字段不完全一样吗?或者kwargs['max_length'] = 104
是我们添加额外参数的点?你知道吗
我认为添加额外选项的更好例子是文档中的
CommaSepField
。它添加了一个separator
参数,因此必须重写deconstruct
方法才能将其添加到kwargs。你知道吗在
HandField
的情况下,max_length
总是104。因此,在kwargs中包含deconstruct
的max_length
方法没有意义,因为它是硬编码的。重写deconstruct
方法并删除max_length
使其更整洁。你知道吗据我所知,文档中说为
HandField
重写deconstruct
是可选的。可以执行HandField(max_length=104)
,但这是不必要的,因为该值将在__init__
中重写。但是,有必要将separator
添加到CommaSepField
中的kwargs中,否则将无法重建字段。你知道吗相关问题 更多 >
编程相关推荐