gpt4 book ai didi

django-rest-framework - DRF-发布到ManyToMany字段

转载 作者:行者123 更新时间:2023-12-04 08:40:23 24 4
gpt4 key购买 nike

在我的Django应用中:

models.py:

class Destination(models.Model):
name=models.CharField(max_length=30)

class Ride(models.Model):
driver = models.ForeignKey('auth.User', related_name='rides_as_driver')
destination=models.ForeignKey(Destination, related_name='rides_as_final_destination')
leaving_time=models.TimeField()
num_of_spots=models.IntegerField()
passengers=models.ManyToManyField('auth.User', related_name="rides_as_passenger")
mid_destinations=models.ManyToManyField(Destination, related_name='rides_as_middle_destination')


序列化器:

class RideSerializer(serializers.ModelSerializer):
driver = serializers.ReadOnlyField(source='driver.username')

class Meta:
model = Ride
fields = ('id', 'driver', 'destination', 'leaving_time',
'num_of_spots', 'passengers', 'mid_destinations')
read_only_fields = ('id', 'driver', 'passengers', 'mid_destinations')


如您所见,mid_destinations是ManyToMany字段。

我的问题是-如何过帐到ManyToMany字段?

到常规字段,我可以从我的android应用中使用这样的json发布:

{ "destination" : "LA", "num_of_spots" : "3", "leaving_time" : "14:35"}

如何过帐到ManyToMany字段?

谢谢你!

最佳答案

两步:
1.从'mid_destinations'列表中删除read_only_fields
2.发送POST数据,例如{"mid_destinations": ["LA", "SF", "SD"], ...}

我假设您正在使用DRF 3。

关于django-rest-framework - DRF-发布到ManyToMany字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31276326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com