Update all Fields of a model, except the key Primary

Asked

Viewed 101 times

0

I am starting the studies in DRF and during a test I came across the following situation: it would be possible to change the fields of a class with the exception of primary key?

My first attempt was to allow the pk to be upgraded so that the other fields would be upgraded, but I was unsuccessful.

I understand that updating pk is not a good practice, but it also does not allow me to update the other class fields. I believe the mistake is silly, but I don’t know how to solve it.

Here’s what’s been done so far:

py.models.

    class Pessoa(models.Model):
        cpf = models.CharField(max_length=100, primary_key=True)
        nome = models.CharField(max_length=100, default='')
        sobrenome = models.CharField(max_length=100, default='')
        cidade = models.CharField(max_length=100, default='')
        estado = models.CharField(max_length=100, default='')
        history = HistoricalRecords()

py serializers.

class VehicleSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Vehicle
        fields = ['cpf','nome','sobrenome','cidade','estado']


        def create(self, validated_data):
            indent, created = Pessoa.objects.update_or_create(
                cpf = validated_data.get('cpf', None),
                defaults={'ident': validated_data.get('ident', None)})
            return ident
  • You have here quite complete documentation, https://www.django-rest-framework.org/tutorial/1-serialization/

  • As for your question update your pk to update the data, it does not exist and neither should you do. Update remaining attributes, yes you can do this.

1 answer

0

If we update a field defined as PK, it is a strong indication that this field should not be a PK. It seems to me that you only wish such a field to be unique. Then I suggest something like this:

 from uuid import uuid4
 class Pessoa(models.Model):
    id = models.UUID(primary_key=True, default=uuid4)
    cpf = models.CharField(max_length=11, unique=True)
    nome = models.CharField(max_length=100, default='')
    sobrenome = models.CharField(max_length=100, default='')
    cidade = models.CharField(max_length=100, default='')
    estado = models.CharField(max_length=100, default='')
    history = HistoricalRecords()

class VehicleSerializer(serializers.HyperlinkedModelSerializer):
  class Meta:
    model = Vehicle
    exclude = ['history','id']

    def create(self, validated_data):
        if Vehicle.objects.filter(cpf=validated_data['cpf']).exists():
           raise serializers.ValidationError('CPF já cadastrado')

        return super(VehicleSerializer, self).create(validated_data)

    def update(self, instance, validated_data):
        validated_data.pop('cpf', None)
        return super(VehicleSerializer, self).update(instance, validated_data)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.