Django自定义域:确切地说,我必须在什么时候编写解构器?

2024-09-28 01:23:31 发布

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

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是我们添加额外参数的点?你知道吗


Tags: ofthetoinfromselfyouif
1条回答
网友
1楼 · 发布于 2024-09-28 01:23:31

我认为添加额外选项的更好例子是文档中的CommaSepField。它添加了一个separator参数,因此必须重写deconstruct方法才能将其添加到kwargs。你知道吗

HandField的情况下,max_length总是104。因此,在kwargs中包含deconstructmax_length方法没有意义,因为它是硬编码的。重写deconstruct方法并删除max_length使其更整洁。你知道吗

据我所知,文档中说为HandField重写deconstruct是可选的。可以执行HandField(max_length=104),但这是不必要的,因为该值将在__init__中重写。但是,有必要将separator添加到CommaSepField中的kwargs中,否则将无法重建字段。你知道吗

相关问题 更多 >

    热门问题