如何创建相关字段?

2024-10-03 13:20:07 发布

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

我有一个模型,你可以在下面看到:

class PriceModel(models.Model):
    name = models.CharField(max_length=12)

PriceModel的id从1增加。我想添加另一个字段,它与id相关。比如我希望它#PM1#PM2。。。表示#PM+id

如何创建相关字段


Tags: name模型idmodelmodelslengthmaxclass
2条回答

I want to add other field, which is related to the id. Such as I want it to #PM1, #PM2... means the #PM + id.

首先,不能保证对于所有数据库系统,id总是以1递增。例如,如果数据库使用事务或其他机制,则可能会回滚事务,因此不会使用相应的id

但是,如果您想要一些始终依赖于字段值的“字段”(这里是id),那么我认为@property可能是一个更好的主意:

class PriceModel(models.Model):
    name = models.CharField(max_length=12)

    @property
    def other_field(self):
        return '#PM{}'.format(self.id)

所以现在如果我们有一些PriceModel,那么some_pricemodel.other_field将返回给定的'#PM123'id123)。好的方面是,如果更改了id,那么属性也会更改,因为每次都是基于字段计算的

一个潜在的问题是,我们可以而不是使用此属性进行查询,因为数据库不知道此类属性的存在。但是,我们可以定义注释:

from django.db.models import Value
from django.db.models.functions import Concat

PriceModel.objects.annotate(
    other_field=Concat(Value('#PM'), 'id')
).filter(
    other_field__icontains='pm1'
)

我认为您可以在模型序列化程序中添加一个特殊字段,而不是在模型中添加一个字段

class PriceModelSerializer(ModelSerializer):
    ....
    show_id = serializers.SerializerMethodField(read_only=True)


    class Meta:
        model = PriceModel

    def get_show_id(self):
        return '#PM' + self.id

相关问题 更多 >