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:
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.