Home > Mobile >  How can I change model id from serializer?
How can I change model id from serializer?

Time:12-17

In order to add data Django db, id should be different so I want to change id value of data model. How can I change model id from serializer ?

I make data_server.py and data_client.py. Using these management/command folder

I checked serialized data is saved after .save command. I can save the data, when I input Id value. But when id value is none, validation test fail and .save make error

error

Unexpected e=AssertionError('You cannot call `.save()` on a serializer with invalid data.'), type(e)=<class 'AssertionError'>

data_server.py

class MyTcpHandler(socketserver.BaseRequestHandler): 
    DBman = DBManager() 
    
    def handle(self):
        print('[%s] connected' % self.client_address[0]) 
        Name = self.registerdbname() 
        msg = self.request.recv(1024) 
        while msg: 
            print([Name], msg.decode())

            stream = io.BytesIO(msg)
            data = JSONParser().parse(stream)
            serializer = DataSerializer(data=data) # create new instance
            serializer = DataSerializer(data, data=data) # update 'data'
            print(serializer)
            print(Data.objects.last().id   1)
            serializer.id = Data.objects.last().id   1
            print(serializer)
            serializer.is_valid()
            serializer.errors
            serializer.validated_data
           
            try: 
                serializer.save()
                print(f'data added : {serializer}')
                if self.DBman.messageHandler(Name, msg.decode()) == -1: 
                    self.request.close() 
                    break 
                msg = self.request.recv(1024) 

            except Exception as e: 
                print(f"Unexpected {e=}, {type(e)=}") 
                break
        
        print('[%s] connection terminated' % self.client_address[0]) 
        self.DBman.removeClient(Name) 

models.py

    class Data(models.Model):
        author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE)
        title = models.CharField(max_length=200)
        temp = models.FloatField(default=0.0)
        humidity = models.FloatField(default=0.0)
        created_date = models.DateTimeField(default=timezone.now)
    
        def __str__(self):
            return f'[{self.pk}]::{self.created_date}::{self.author}::{self.title}'
    
        def get_absolute_url(self):
            return f'/data/{self.pk}/'
    
    class DataSerializer(serializers.ModelSerializer):
        id = serializers.IntegerField(write_only=False)
        class Meta:
            model = Data
            fields = '__all__'

CodePudding user response:

If you want to add your data to database, you can use Data.objects.create(data=data) the id is incremented automatically, you don't need to update it yourself.

Hope this answers your question.

CodePudding user response:

Let me clarify what I think is happening, and you can tell me if this is answering the wrong question :)

  1. You get the data in, including an id
  2. You want to save this as a new record, including a new ID?

If that is the case, then make sure to set the id to None before doing a save, and Django will assign a new key value when saving to the DB. There is no need to try and work it out for yourself - just make sure there isn't an existing one there. You could probably just pop the id off the serializer completely as well.

  • Related