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?
If you want to load from legacy fixture, you could build some intermediate model/table, convert file or customize dumpdata command. Fool dumpdata is possible, as following, but hmm…
Or you could add customized serializer to public serializers and mainly override its
Deserializerfunction to work w/ properties that you have. Mainly override to tweak two lines inDeserializerinsidedjango/core/serializers/python.py