0

I have the following models in my application:

class User(models.Model):
    name = models.CharField(max_length=100)
    birth_date = models.DateField()
    address = models.CharField(max_length=200)

class Device(models.Model):
    description = models.CharField(max_length=200)
    location = models.CharField(max_length=200)
    max_energy_consumption = models.FloatField()
    avg_energy_consuumption = models.FloatField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

A user can have multiple devices, hence the foreign key user in the Device class. These are my serializers:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'

class DeviceSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = Device
        fields = '__all__'

I am using a default ModelViewSet for CRUD operations:

class UserViewSet(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class DeviceViewSet(ModelViewSet):
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer

In my database, the devices table has a user_id column, like it should. When I open the Django API in the browser, I see this:

enter image description here

In the POST form, there is no field for user_id. Shouldn't it be one? How am I supposed to add a device through a request and specify which user it belonges to? Like this it just puts null in the user field, which is not what I want. I want to specify to a device which user it belonges to at creation.

Oros Tom
  • 111
  • 1
  • 7
  • 1
    This is because `read_only` is set to true for `user` in `DeviceSerializer` – Brian Destura Oct 31 '21 at 22:14
  • Thank you! But this way it makes me insert a entire user model along with a device. It puts me to insert a name, birth_date and address, but I don't want to create a new model. I just want to specify the entire device model + a user_id (an already created user). And now, If I am to insert something, I have the following error: Write an explicit `.create()` method for serializer `app.serializers.DeviceSerializer`, or set `read_only=True` on nested serializer fields. – Oros Tom Nov 01 '21 at 06:09
  • Ah that is because you used `UserSerializer` in `DeviceSerializer`, so it expects user object with all the details. In that case try to remove the line `user = UserSerializer(read_only=True)`. It should then ask you to just put in a user id. This should be the default behaviour – Brian Destura Nov 01 '21 at 06:11
  • Yes, this is the behaviour I was looking for, thank you! But now how can I do so when I get my users, to have a list of what devices that user has? – Oros Tom Nov 01 '21 at 06:54
  • [This](https://stackoverflow.com/questions/29950956/drf-simple-foreign-key-assignment-with-nested-serializers) might help – Brian Destura Nov 01 '21 at 10:40

0 Answers0