存储具有相关模型的对象会导致IntegrityError:空值违反了非空约束

时间:2019-02-22 14:55:03

标签: django django-models tastypie

我在使用Django和Deliciouspie时遇到以下问题。奇怪的是,在大约一年左右的时间里,以下程序完美无缺地工作了。现在,当我尝试在Car上编辑Owner并存储Owner时,出现此错误:

  

django.db.utils.IntegrityError:“ car_id”列中的空值违反了非空约束   详细信息:失败行包含(55,test,53,null)。

我知道我可以将模型car上的字段Wheel更改为可为空,但我确实想保持此关系的定义。奇怪的是,当我将该字段更改为可空以进行测试时,该ID在我的数据库中设置。然后,当我进行另一次编辑时,数据库条目不会更新,而是会创建一个新条目。该条目再次包含正确的ID,但旧条目将丢失它,并且该字段保留为空白。

在汽车对象上对其进行两次编辑后,表wheel的外观如下:

postgres=# TABLE wheel;
id | value | wheel_type_id | car_id
---+-------+---------------+--------
53 | abc   |            53 |
54 | def   |            53 |     11
(2 rows)

相反,我想要的结果是这样:

postgres=# TABLE wheel;
id | value | wheel_type_id | car_id
---+-------+---------------+--------
53 | def   |            53 |     11
(1 row)

型号:

class Owner(models.Model):
    id = models.AutoField(primary_key=True)

class Car(models.Model):
    owner = models.OneToOneField('Owner', null=True, related_name='car',
                                  on_delete=models.CASCADE)
    ready = models.BooleanField(default=False)

class Wheel(models.Model):
    car = models.ForeignKey(Car, related_name='wheel',
                            on_delete=models.CASCADE)
    wheel_type = models.ForeignKey(WheelType, related_name='names',
                                   on_delete=models.CASCADE)
    value = models.CharField(max_length=500)

Tastypie资源:

class OwnerResource(ModelResource):
    car = fields.ToOneField('CarResource', null=True, full=True,       
                             attribute='car')

class CarResource(ModelResource):
    wheels = fields.ToManyField('WheelResource', 'wheels', null=True,
                                 blank=True, full=True)

class WheelResource(ModelResource):
    wheeltype = fields.ForeignKey('WheelTypeResource',   
                                  'wheel_type', full=False)


    class Meta:
        queryset = Wheel.objects.all()
        allowed_methods = ['get']
        ordering = ['modified']
        excludes = ['id']
        include_resource_uri = False
        limit = 100
        authorization = Authorization()
        always_return_data = True

示例请求:

fetch("http://0.0.0.0:8000/api/v1/owner/1/", {
    "credentials": "include",
    "headers": {
        "accept": "application/json",
        "accept-language": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7",
        "cache-control": "no-cache",
        "content-type": "application/json",
        "pragma": "no-cache",
        "x-csrftoken": "3sarlkh0giQ7yqhTSclCivfEsSvs5R3a7gTw0pw293v80ypCT6n3Drm8AhQDx3GB"
    },
    "referrer": "http://0.0.0.0:8000/backend/owner/1",
    "referrerPolicy": "no-referrer-when-downgrade",
    "body": "{\"car\":{\"resource_uri\":\"/api/v1/car/3/\",\"wheels\":[{\"wheeltype\":\"/api/v1/wheeltype/identificationInfo/\",\"value\":\"abc\"}]},\"resource_uri\":\"/api/v1/owner/1/\",}",
    "method": "PATCH",
    "mode": "cors"
});

有人知道为什么在保存对象时未定义car_id,但是使该字段可为空时仍然被设置吗?开始认为这可能是Tastypie或Django的错误。

0 个答案:

没有答案