相关对象查询django rest框架

时间:2018-05-04 00:07:45

标签: django nested-query django-related-manager

我有以下型号

class STUser(AbstractBaseUser):
    email = models.EmailField(unique=True)
    name = models.CharField(max_length=255)
    companyname = models.CharField(max_length=200, blank=True, null=True)
    ...

class VenuePermissions(models.Model):
    user = models.ForeignKey(STUser, on_delete=models.CASCADE)
    venue = models.ForeignKey(Venue, on_delete=models.CASCADE) 
    signupvaildatestring = models.CharField(max_length=200, blank=True, null=True)
    ...

我想获取所有STUser个对象并获取所有权限。

所以我想要抓住所有VenuePermissions个对象。并获取每个场地的uservenue对象

我可以通过两种方式做到这一点。使用VenuePermissions_set上的STUser属性,但是当它只是pk值时,如何抓住该地点?

或者专注于VenuePermissions对象并从pk值中获取用户和场地但是如何?

我记得嵌套查询,我在浏览代码中做了一个。

这是一个例子:

 rooms = Room.objects.filter(venue=OuterRef('pk'), sixtyroundseatingoption= True)
            venuelist = venuelist.annotate(sixtyrounds=Exists(rooms))
            venuelist = venuelist.filter(Q(sixtyrounds = True) | Q(fullbuyoutsixtyroundseatingoption = True))

我在

之前在序列化器中完成了设置对象

示例序列化器:

class RoomAndImageSerializer(serializers.ModelSerializer):
    roomimage_set = RoomImageSerializer(many=True, read_only=True)
    class Meta:
        model = Room
        fields = ('pk','name')

对此查询的任何帮助都将不胜感激!

所以这就是我目前正在尝试的,如果有效,我会发一个答案:

class VenueUserList(ListAPIView):
    serializer_class = VenueUserListSerializer
    queryset = VenuePermissions.objects.select_related('user').select_related('venue').filter(signupvaildatestring=None)

class VenueUserListSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    venue = VenueSerializer()
    class Meta:
        model = VenuePermissions
        fields = ('user', 'venue', 'isvenueviewer', 'isvenueeventplanner', 'isvenueadministrator')

1 个答案:

答案 0 :(得分:0)

这是答案。但是我仍然需要按用户分组场地。正在努力。

class VenueUserList(ListAPIView):
    serializer_class = VenueUserListSerializer
    queryset = VenuePermissions.objects.select_related('user').select_related('venue').filter(signupvaildatestring=None)

class VenueUserListSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    venue = VenueSerializer()
    class Meta:
        model = VenuePermissions
        fields = ('user', 'venue', 'isvenueviewer', 'isvenueeventplanner', 'isvenueadministrator')