简体   繁体   English

获取 NOT NULL 约束失败:DRF 中的locations_location.city_id

[英]Getting NOT NULL constraint failed: locations_location.city_id in DRF

When I try to create an object through DRF serailizers in my api, I get the error NOT NULL constraint failed: locations_location.city_id .当我尝试通过我的 api 中的 DRF serailizers 创建一个对象时,我收到错误NOT NULL constraint failed: locations_location.city_id

I looked at a similar here and the solution provided seems to be exactly what I had to begin with.我在这里查看了类似的内容,提供的解决方案似乎正是我必须开始的。

My models:我的模型:

class City(models.Model):
    code = models.CharField(max_length=4, default="", blank=False, unique=True)
    name = models.CharField(max_length=40, default="", blank=False, unique=True)
    time_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name}, ({self.code})"

    class Meta:
        verbose_name = "City"
        verbose_name_plural = "Cities"


class Location(models.Model):
    status_choice = (
        ("Available", "Available"),
        ("Unavailable", "Unavailable"),
        ("Active", "Active"),
    )
    city = models.ForeignKey(City, on_delete=models.CASCADE, related_name="locations")
    name = models.CharField(max_length=256, default="", blank=True)
    rent = models.DecimalField(max_digits=7, decimal_places=2)
    email = models.EmailField(max_length=64)
    phone = models.CharField(max_length=20, default="", blank=True)
    lon = models.DecimalField(max_digits=7, decimal_places=5, blank=True, null=True)
    lat = models.DecimalField(max_digits=7, decimal_places=5, blank=True, null=True)
    street_number = models.CharField(max_length=50, null=True)
    street_name = models.CharField(max_length=50, null=True)
    postal_code = models.CharField(max_length=50, null=True)
    status = models.CharField(max_length=50, choices=status_choice, default="Available")
    time_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.name} {self.status}"

My serailizers:我的serailizers:


class CitySerializer(serializers.ModelSerializer):
    locations = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = City
        fields = "__all__"

    def create(self, validated_data):
        return City.objects.create(**validated_data)


class LocationSerializer(serializers.ModelSerializer):
    location_events = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    booked_days = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Location
        fields = "__all__"
        depth = 1

    def create(self, validated_data):
        city = serializers.PrimaryKeyRelatedField(  # noqa
            many=False, queryset=City.objects.all()
        )
        return Location.objects.create(**validated_data)

This is the fake test data passed to the api in POST request:这是在 POST 请求中传递给 api 的假测试数据:

{
 "name": "Darmstadt Hotel", 
 "city": 1,
 "email": "fischernicolai@nohlmans.de", 
 "phone": "+49(0)7219 993238", 
 "rent": 275.38, 
 "lat": 52.9427, 
 "lon": 12.1076, 
 "street_name": "Eimerstra\\u00dfe", 
 "street_number": "34", 
 "postal_code": "80843", 
 "status": "Available"
}

A city with id of 1 exists in the database and is accessible through the api.数据库中存在一个 id 为 1 的城市,可通过 api 访问。

Firstly, you have the city field in your LocationSerializer inside the create method, that must be an error?首先,你在你的LocationSerializercreate方法中有 city 字段,那一定是一个错误? It should be the line below booked_days = ... .它应该是booked_days = ...下方的行。 I'm not sure this will solve the problem however.但是,我不确定这会解决问题。

class LocationSerializer(serializers.ModelSerializer):
    location_events = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    booked_days = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    city = serializers.PrimaryKeyRelatedField(  # noqa
        many=False, queryset=City.objects.all()
    ) # Move it here

    class Meta:
        model = Location
        fields = "__all__"
        depth = 1

    def create(self, validated_data):
        return Location.objects.create(**validated_data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 DRF POST 给出 NOT NULL 约束失败 - DRF POST giving NOT NULL constraint failed NOT NULL约束失败:loginpage_location.org_id - NOT NULL constraint failed: loginpage_location.org_id “ city_id”列中的空值违反了非空约束 - null value in column “city_id” violates not-null constraint Django:“ NOT NULL约束失败”。user_id - Django: “NOT NULL constraint failed” .user_id 我在 /post/new/ NOT NULL 约束失败处收到 IntegrityError:blog_post.author_id - I'm getting an IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id 我不断收到此错误 NOT NULL constraint failed: lists_listcreate.user_id - I keep getting this error NOT NULL constraint failed: lists_listcreate.user_id Django-为什么会出现此IntegrityError:NOT Null约束失败:Restaurants_restaurantlocation.owner_id? - Django - Why am I getting this IntegrityError: NOT Null constraint failed: restaurants_restaurantlocation.owner_id? 获取数据库错误,NOT NULL 约束失败 - Getting database error, NOT NULL constraint failed IntegrityError:“city_id”列中的空值违反非空约束 - IntegrityError: null value in column “city_id ” violates not-null constraint null “user_id”列中的值违反了非空约束 DRF - null value in column "user_id" violates not-null constraint DRF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM