我有一个带有外键的模型,当我试图创建一个新对象时,它会抛出一个错误。我认为外键字段(user_profile_id)出于某种原因是空的(不应该是空的),当尝试创建时,会抛出错误(字段永远不应该是空的)。这是我得到的错误:
IntegrityError at /api/sensors/
NOT NULL constraint failed: sensors_api_sensor.user_profile_id
Request Method: POST
Request URL: http://127.0.0.1:8000/api/sensors/
Django Version: 2.2
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: sensors_api_sensor.user_profile_id
Exception Location: /home/vagrant/env/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 383
Python Executable: /home/vagrant/env/bin/python3
Python Version: 3.6.9
Python Path:
['/vagrant',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/home/vagrant/env/lib/python3.6/site-packages']
Server time: Mon, 21 Dec 2020 08:29:01 +0000
models.py:
class Sensor(models.Model):
"""Database model for users' sensors"""
user_profile = models.ForeignKey(
settings.AUTH_USER_MODEL, # first argument is the remote model for this foreign key
on_delete=models.CASCADE # if ForeignKey is deleted, delete all associations
)
name = models.CharField(max_length=255)
sensor_type = models.CharField(max_length=255)
surrounding = models.CharField(max_length=255)
latitude = models.FloatField()
longitude = models.FloatField()
created_at = models.DateTimeField(auto_now_add=True, null=False) # auto adds creation timestamp UTC for each object
updated_at = models.DateTimeField(auto_now=True, null=False)
# other fields required
REQUIRED_FIELDS = ['user_profile','name','type','surrounding']
# model to string conversion method
def __str__(self):
"""Return the model as a string"""
return self.name # returns the sensor name
序列化程序.py
class SensorSerializer(serializers.ModelSerializer):
"""Serializes a sensor object"""
class Meta:
# points serializer to WeatherSensor model
model = models.Sensor
# list fields you want to make accessible from WeatherSensor model in tuple
fields = ('id', 'user_profile', 'name', 'sensor_type', 'surrounding',
'latitude', 'longitude', 'created_at', 'updated_at')
# make foreign key read only by using extra keyword args variable
extra_kwargs = {'user_profile': {'read_only': True}}
views.py
class SensorListApiView(APIView):
"""Sensor List API View for list and create"""
serializer_class = serializers.SensorSerializer
def post(self, request):
"""Create a weather sensor"""
# self.serializer_class comes with APIView that retrieves serializer class for our review
serializer = self.serializer_class(data=request.data)
# validate input as per serializer class spec
if serializer.is_valid():
# can retrieve any field that is defined in our serializer
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
# use status library to pass human-readable error
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
设置.py
...
# Model Overrides
AUTH_USER_MODEL = 'profiles_api.UserProfile'
在测试一些奇怪的东西时,我观察到:
user = models.UserProfile.objects.get(id=1)
ws = models.Sensor.objects.create(
user_profile=user, name='MoistureSensor1',
sensor_type='MoistureSensor', surrounding='greenhouse',
latitude=37.7749, longitude=122.4194,
created_at=timezone.now(), updated_at=timezone.now()
)
ws.save()
尝试从序列化程序中删除
user_profile
,然后:您希望使用序列化程序创建与request.user相关的对象
您在这里需要做的非常简单:
请小心,因为我在代码中没有看到检查用户是否实际登录的地方
相关问题 更多 >
编程相关推荐