python Django更改了ManyToManyField的顺序,但必须与post请求中的顺序完全相同

yfwxisqw  于 2023-02-28  发布在  Python
关注(0)|答案(2)|浏览(532)

我有两个模型(车辆和站点)。我想为每辆车创建路线,所以我在我的车辆模型中添加了manyToManyField。每当我发送post请求时,在json对象中列出了几个站点django会扰乱顺序,它不会像那样工作。我必须做什么来保存对象,使其与post请求中提供的顺序完全相同?
型号:

class Vehicle(models.Model):
    nr = models.CharField(max_length=24)
    route = models.ManyToManyField(Stop, related_name='stop')

class Stop(models.Model):
    name = models.CharField(max_length=64)

serializers.py:

class VehicleSerializer(DynamicDepthSerializer):

    class Meta:
        model = TrainLibrary
        fields = ['nr','route']
z9smfwbn

z9smfwbn1#

您需要的是在多对多关系中的through-table/join-table中保持顺序。
您的模型将类似于以下内容:

class Vehicle(models.Model):
    nr = models.CharField(max_length=24)
    route = models.ManyToManyField(Stop, related_name='stop', through="RouteStop")

class Stop(models.Model):
    name = models.CharField(max_length=64)

class RouteStop(models.Model):
    vehicle = models.ForeignKey("Vehicle", on_delete=models.CASCADE)
    stop = models.ForeignKey("Stop", on_delete=models.CASCADE)
    order = models.PositiveIntegerField()
    
    class Meta:
        ordering = ["order"]
        unique_together = ('vehicle', 'stop')

现在,在序列化器中,您可以执行以下操作:

class VehicleSerializer(serializers.ModelSerializer):
    route = serializers.SerializerMethodField()

    class Meta:
        model = Vehicle
        fields = ['nr', 'route']

    def get_route(self, obj):
        # you can use whatever representation you want.
        return [stop.name for stop in obj.routestop_set.all().order_by('order')]

在这里,我只显示站点名称,但是您可以使用任何其他序列化器来序列化信息。

1tu0hz3e

1tu0hz3e2#

我发现最好的选择是django-sortedm 2 m库。

相关问题