带有外键的Django模型在保存时抛出错误

2024-05-17 16:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有外键的模型,当我试图创建一个新对象时,它会抛出一个错误。我认为外键字段(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'

在测试一些奇怪的东西时,我观察到:

  1. 当使用authtoken的modheader在浏览器中进行本地测试时,我在提交时收到上述错误
  2. 在Django Shell中,序列化程序是有效的,但当我保存序列化程序时,会出现上述错误
  3. 在Django Shell中,我可以使用以下代码成功创建对象:
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()

Tags: namepyapiidmodelmodelslib错误
2条回答

尝试从序列化程序中删除user_profile,然后:

if serializer.is_valid():
    serializer.save(user_profile=request.user)

您希望使用序列化程序创建与request.user相关的对象

您在这里需要做的非常简单:

  1. 重写create()方法
  2. 使用序列化程序上下文,从create()方法的视图中获取request.user
# serializers.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}}
    
    def create(self, validated_data):
        user = self.context["request"].user
        sensor = models.Sensor.objects.create(user_profile=user, **validated_data)
        return sensor


# 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, context={"request":request})
        # You need to pass the request in the context.
        # etc...

请小心,因为我在代码中没有看到检查用户是否实际登录的地方

相关问题 更多 >