qg_java_17137
qg_java_17137

Reputation: 3589

How to create the related field?

I have a Model you see bellow:

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

the PriceModel's id is increased from 1. I want to add other field, which is related to the id. Such as I want it to #PM1, #PM2... means the #PM + id.

How to create the related field?

Upvotes: 2

Views: 52

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477533

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

First of all, it is not guaranteed that for all database systems, the id is always incremented with one. For example if the database works with transactions, or other mechanisms, it is possible that a transaction is rolled back, and hence the corresponding id is never taken.

If you however want some "field" that always depends on the value of a field (here id), then I think a @property is probably a better idea:

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

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

So now if we have some PriceModel, then some_pricemodel.other_field will return a '#PM123' given (id is 123). The nice thing is that if the id is changed, then the property will change as well, since it is each time calculated based on the fields.

A potential problem is that we can not make queries with this property, since the database does not know such property exists. We can however define an annotation:

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'
)

Upvotes: 2

aircraft
aircraft

Reputation: 26924

I think you can in your model serializer add a special field, rather than add a field in the Model.

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


    class Meta:
        model = PriceModel

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

Upvotes: 1

Related Questions