[Python] Convert property to django model field

Discussão em 'Python' iniciado por Stack, Junho 8, 2025.

  1. Stack

    Stack Membro Participativo

    Is there any way to create virtual model field in django?

    For example I have

    class A(models.Model):
    field_1 = models.CharField(max_length=100)
    field_2 = models.CharField(max_length=100)

    @apply
    def virtual_field():
    def fget(self):
    return self.field1 + '/' + self.field2
    def fset(self, value):
    self.field_1, self_field_2 = value.split('/')
    return True
    return property(**locals())


    Now, if I will run:

    a = A()
    a.virtual_field = '5/5'
    a.save()


    It will work fine.

    But I have a dump, where I have model A with virtual_field value - on serialization I've got an error "A object has no virtual_field"... How I can cheat serializer and tell it, that virtual_field exists?

    Continue reading...

Compartilhe esta Página