简体   繁体   中英

Custom fields in Django models

Is it possible to have custom fields (non-model fields) in a django model. For instance, I have a the following model:

class Patient(models.Model):
    firstName = models.CharField(max_length=100, blank=True, default='')
    lastName = models.CharField(max_length=100, blank=True, default='')
    occupation = models.CharField(max_length=100, blank=True, default='')
    gender = models.CharField(max_length=50, blank=True, default='')
    dateOfBirth = models.DateField(blank=True, default=date.today)
    address = AddressField(blank=True, null=True)

Address is a non-model field. I also have this serializer:

class PatientSerializer(serializers.Serializer):
    firstName = serializers.CharField()
    lastName = serializers.CharField()
    occupation = serializers.CharField()
    gender = serializers.CharField()
    dateOfBirth = serializers.DateField()
    address = serializers.SerializerMethodField()

    def create(self, validated_data):
        """
        Create and return a new patient
        """
        return Patient.objects.create(**validated_data)

    def get_address(self, obj):
        return obj.address

I tried to set it as a SerializerMethodField in my serializer, but this is not working correctly, address is always null. Just for information, I'm using Django-nonrel since I'm using a mongodb database.

Why not use the editable attribute of the field? https://docs.djangoproject.com/en/1.10/ref/models/fields/#editable

class Patient(models.Model):
    firstName = models.CharField(max_length=100, blank=True, default='')
    lastName = models.CharField(max_length=100, blank=True, default='')
    occupation = models.CharField(max_length=100, blank=True, default='')
    gender = models.CharField(max_length=50, blank=True, default='')
    dateOfBirth = models.DateField(blank=True, default=date.today)
    address = AddressField(blank=True, null=True, editable=False)

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM