如何在Django模型中向外键字段添加和更新数据

时间:2018-11-20 13:30:32

标签: django python-3.x django-models

我有两个与外键有关的模型。

class BikeModel(models.Model):
    City = models.ForeignKey(CityForBike, on_delete=models.CASCADE)
    BikeModels = models.CharField(default='', max_length=50)
    Image = models.ImageField(upload_to='bike_images', blank=True, null=True, default='https://www.urbandrive.co.in/Admin/API/UploadedFiles/CarImage/44b150b3-f61a-41b5-afd8-34ded18fa980.png')

    class Meta:
        verbose_name_plural = 'BikeModels'

    def __str__(self):
        return self.BikeModels

class CityForBike(models.Model):
    CityForCars = models.CharField(default="",max_length=50)

    class Meta:
        verbose_name_plural = 'CityForBikes'

    def __str__(self):
        return self.CityForCars

,我想将数据插入BikeModel。但这给了我错误。

 AssertionError: You cannot call `.save()` on a serializer with invalid data.

我想知道如何将数据插入外键字段。

if request.method == 'POST':
    import pdb;
    pdb.set_trace()
    input_data = json.loads(request.read().decode('utf-8'))
    print(input_data)
    serializer = serializers.BikeModelSerializer(data=input_data)
    if serializer.is_valid():
        serializer.save()
        return render(request, "bike_model_add.html", {'car_city': car_city}, status=200)

这是我正在发送的数据。

{'City': 'testo', 'BikeModels': 'ds'}

这是我的序列化器

class CityForBikeSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CityForBike
        fields = '__all__'

class BikeModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.BikeModel
        fields = '__all__'

1 个答案:

答案 0 :(得分:0)

如果要在自行车序列化程序中通过城市名称识别城市,则需要使用SlugRelatedField

class BikeModelSerializer(serializers.ModelSerializer):
    City = serializers.SlugRelatedField(slug_field='CityForCars')

    class Meta:
        model = models.BikeModel
        fields = '__all__'