1

我有一个模型,其中一个Vehicle表有更多Wheels表。我试图在单个字段中显示车辆和相关车轮表中第一个车轮的信息。我已经看到该F功能可能很有用,但我找不到正确的配置以使其正常工作。这些表通过另一个名为的字段相关联,该字段colour在表中声明为外键Wheels


    class VehicleListView(ListView):
        template_name = 'vehicle.html'
        queryset = Vehicle.objects.all()

        queryset = queryset.annotate(wheel1_name = F('Wheels__wheel_name'))

        def get_context_data(self, **kwargs):
            context = super().get_context_data(**kwargs)
            return context

我想要这条线


    queryset = queryset.annotate(wheel1_name = F('Wheels__wheel_name'))

返回每辆车的第一个车轮名称列表,以便我可以遍历它并将其显示在表格中。

models.py

class Vehicle(models.Model):
    vehicle_id = models.AutoField(primary_key=True)
    vehicle_name = models.CharField(max_length=100)
    color = models.CharField(max_length=100)

class Wheels(models.Model):
    wheels_id = models.AutoField(primary_key=True)
    color = models.ForeignKey(Vehicle, null=True, on_delete=models.SET_NULL,
                                  db_column='color')
    wheel_name = models.CharField(max_length=100)
4

1 回答 1

1

所以我稍微修改了你的代码,设置了数据库,创建了 2 个Vehicle对象,每个对象有 2 个相关Wheels对象,所以Wheels总共有 4 个对象。

我添加了一个函数,用于查询Wheel某个对象的第一个相关Vehicle对象。

# models.py

class Vehicle(models.Model):
    vehicle_id = models.AutoField(primary_key=True)
    vehicle_name = models.CharField(max_length=100)
    color = models.CharField(max_length=100)

    # this function returns a slice of the resulting queryset which contains
    # the first related Wheels object for each Vehicle object
    def get_first_wheels(self):
        return Wheels.objects.filter(color=self).order_by('wheels_id')[:1]


class Wheels(models.Model):
    wheels_id = models.AutoField(primary_key=True)
    color = models.ForeignKey(Vehicle, null=True, on_delete=models.SET_NULL)
    wheel_name = models.CharField(max_length=100)

我使用Django 序列化程序来序列化数据。为了获得第一个相关Wheels对象,我使用了一个SerializerMethodField()这样调用get_first_wheels()函数的对象models.py

# serializers.py

class WheelsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Wheels
        fields = ('wheels_id', 'color', 'wheel_name')


class VehicleSerializer(serializers.ModelSerializer):
    first_wheel = serializers.SerializerMethodField(read_only=True)

    def get_first_wheel(self, model):
        qs = model.get_first_wheels()
        return WheelsSerializer(qs, many=True).data

    class Meta:
        model = Vehicle
        fields = ('vehicle_id', 'vehicle_name', 'color', 'first_wheel')

我稍微改变了你的看法,改用了 a ModelViewSet

# views.py

class VehicleViewSet(viewsets.ModelViewSet):
    serializer_class = VehicleSerializer
    queryset = Vehicle.objects.all()

我去使用 aDefaultRouter()来注册端点,如下所示:

# urls.py

from rest_framework import routers
# import ViewSet here

router = routers.DefaultRouter()

router.register(r'vehicles`, views.VehicleViewSet, base_name='vehicle')

然后我运行了以下命令:

  • manage.py makemigrations

  • manage.py migrate

  • manage.py runserver

我创建了 2 个Vehicle对象,每个对象有 2 个相关Wheels对象。

当我进入http://127.0.0.1:8000/vehicles/浏览器时,它会返回所有Vehicle对象及其第一个相关Wheels对象,如下所示:

[
    {
        "vehicle_id": 1,
        "vehicle_name": "BMW",
        "color": "Blue",
        "first_wheel": [
            {
                "wheels_id": 1,
                "color": 1,
                "wheel_name": "BMW1"
            }
        ]
    },
    {
        "vehicle_id": 2,
        "vehicle_name": "Ferrari",
        "color": "Red",
        "first_wheel": [
            {
                "wheels_id": 3,
                "color": 2,
                "wheel_name": "Ferrari1"
            }
        ]
    }
]
于 2019-07-17T17:04:54.203 回答