迭代查询集并用其相关对象替换外键django rest framework

时间:2018-05-04 21:45:23

标签: django django-rest-framework iteration django-queryset prefetch

我有以下型号:

B

然后我将相关的class STUser(AbstractBaseUser): email = models.EmailField(unique=True) name = models.CharField(max_length=255) ... class VenuePermissions(models.Model): user = models.ForeignKey(STUser, on_delete=models.CASCADE) venue = models.ForeignKey(Venue, on_delete=models.CASCADE, blank=True, null=True) ... class Venue(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=1500, null=True, blank=True) ... 对象预取到视图中的venuepermission对象

STUser

然后我想获取返回的查询集并将class VenueUserList(APIView): def get(self, request, *args, **kwargs): objects = STUser.objects.prefetch_related('venuepermissions_set').all() ... FK替换为其对象。

venue

但我的做法显然是错误的。如何正确访问查询集的字段并更改其值?

如你所见,我需要做两次。一旦访问当前对象permission_set,再次访问该permission_set场地字段并覆盖它。

我不希望任何改变数据库。这只是为了返回值。

更新:

我进行了以下更改以访问各个字段:

 for item in objects:
        for permission in item_venuepermissions_set:
            permission_venue = Venue.objects.get(pk=permission_venue)
    print(repr(objects))
    ...
    return Response({})

我遇到的新错误是:

for item in objects:
            for permission in item.venuepermissions_set:
                permission.venue = Venue.objects.get(pk=permission.venue)
        print(repr(objects))
        return Response({})

试图解决

1 个答案:

答案 0 :(得分:0)

今天回答我的所有问题:

class VenueUserList(APIView):
    def get(self, request, *args, **kwargs):
        objects = STUser.objects.prefetch_related('venuepermissions_set').all()
        for item in objects:
            for permission in item.venuepermissions_set.all():
                permission.venue = Venue.objects.get(pk=permission.venue_id)
        return Response({})

是这样做的方法