DRF:提供动态默认字段值的最佳方式?

DRF: Best way to supply a dynamic default field value?

我们的 SAAS 站点使用 DRF 后端和 Vue 前端。我们有一些字段不需要来自用户的值,但需要数据库中的值。我想知道提供此类动态默认值的最佳位置在哪里。我在其他帖子中读到 "save() is not always called" - 尽管我还不知道在什么情况下不会调用它。

因此,考虑以下模型:

class Tenant(models.Model):

    name = models.CharField(max_length=100)
    subdomain = models.CharField(max_length=100, blank=True, null=True)
    schema_name = models.CharField(max_length=63, unique=True)

在这种情况下,只需要 "name"(来自用户); "schema_name",如果在前端表格中留空,可以从 "name" 派生(将其转换为小写)。同样,"subdomain" 可以从 "schema_name" 导出。 "subdomain" 可以是 blank/null,因为 "public" 架构不引用子域,但除 "public" 以外的所有租户都需要它的值。)

那么,如果在创建或更新租户时这些字段为空,我应该将填充这些字段的代码放在哪里?

除非您进行批量更新,否则将调用保存,因此您可以将它放在那里就好了。如果有选择,我宁愿不选择,但有时没有。

如果想放到serializer中,可以这样写,然后用一个ModelViewSet来处理细节:

class TenantSerializer(ModelSerializer):
    name = CharField(required=True, min_length=1)
    sub_domain = CharField(required=False)

    class Meta:
        model = Tenant
        fields = ['id', 'name', 'sub_domain']

    def validate(self, attrs):
        # attrs is all fields parsed & validated on a per-field level
        # in here you can do validation that depends on >1 field
        # values returned will be passed to the serializer create()/update()
        # via the common serializer.save() method
        if self.instance:
            # doing an update, maybe different logic, or just ignore?
        else:
            if not attrs.get('sub_domain'): # missing or blank
                attrs['sub_domain'] = parse_subdomain(attrs.get('name'))
        return attrs