Django REST:如何过滤相关集?

时间:2017-11-22 12:55:25

标签: django serialization django-rest-framework

我正在尝试创建一个包含城市的Serializer,以及属于当前用户的每个城市旅行列表。问题在于我得到了所有旅行,而不仅仅是用户。

我的期望是,如果用户在伦敦两次,一次在布拉格:

[{<serialized London>,'trips':[<serialized the two London trips>]},
{<serialized Prague>, 'trips':[<serialized one trip to Prague]}]

现在我将所有旅行都与城市联系起来。

型号:

class City(models.Model):
    place_id = models.CharField(max_length=1000, unique=True, null=True, blank=True)
    lat = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True)
    lng = models.DecimalField(max_digits=6, decimal_places=3, db_index=True, null=True, blank=True)

class Trip(models.Model):
    user = models.ForeignKey('auth.User', related_name='trips')
    city = models.ForeignKey('locations.City', related_name='trips')
    date_from = models.DateField(default=now)
    date_to = models.DateField(default=now)
    detail = models.TextField(null=True, blank=True)

查看:

def ajax_get_my_trips(request):
    trips = Trip.objects.filter(user=request.user)
    cities = City.objects.filter(trips__in=trips)
    response = MyCityTripsSerializer(cities,many=True).data
    return JsonResponse(response, safe=False)

串行器:

class MyTripsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Trip
        fields = ('date_from', 'date_to', 'detail')

    def get_queryset(self):
        user = self.request.user
        return Trip.objects.filter(user=user)


class MyCityTripsSerializer(serializers.ModelSerializer):
    trips = MyTripsSerializer(many=True)

    class Meta:
        model = City
        fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address', 'trips')

你知道怎么做吗?

1 个答案:

答案 0 :(得分:0)

class MyTripsSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all())
    city = serializers.PrimaryKeyRelatedField(queryset=City.objects.all())
    class Meta:
        model = Trip
        fields = ('date_from', 'date_to', 'detail')

    def get_queryset(self):
        user = self.request.user
        return Trip.objects.filter(user=user)


class MyCityTripsSerializer(serializers.ModelSerializer):
    trips = MyTripsSerializer(many=True)

    class Meta:
        model = City
        fields = ('place_id', 'lat', 'lng', 'number_of_users_here_now', 'formatted_address', 'trips')


class Trip(models.Model):
    user = models.ForeignKey('auth.User', related_name='user_trips')
    city = models.ForeignKey('locations.City', related_name='trips')
    date_from = models.DateField(default=now)
    date_to = models.DateField(default=now)
    detail = models.TextField(null=True, blank=True)

每个ForeignKey的相关名称必须是唯一的。