我想创建一个自定义的查询集类,该类返回不同的字段以预定义两种情况。
DateField
比今天大时如果更大,则返回所有字段,否则仅返回date_to_open
和post_name
字段。
views.py
class GroupDetail(generics.RetrieveAPIView):
serializer_class = serializers.GroupDetailsSerializer
permission_classes = (IsAuthenticated, )
def greater(self):
return models.Group.objects.filter(shared_to=self.request.user,
date_to_open__gt=timezone.now()).exists()
def get_queryset(self, *args, **kwargs):
if self.greater():
query_set = models.Group.objects.filter(shared_to=self.request.user,
date_to_open__gt=timezone.now())
else:
query_set = SPECIFIC FIELDS
return query_set
serializers.py
class GroupDetailsSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.name')
images = GroupImageSerializer(many=True, read_only=True)
shared_to = serializers.SlugRelatedField(queryset=models.UserProfile.objects.all(),
slug_field='name', many=True)
class Meta:
model = models.Group
fields = ('id', 'group_name', 'owner', 'group_text', 'created_on', 'date_to_open', 'shared_to',
'images', )
答案 0 :(得分:1)
好的。感谢@ArakkalAbu评论,我刚刚重写了get_serializer_class()
views.py
class GroupDetail(generics.RetrieveAPIView):
queryset = models.Group.objects.all()
serializer_class = serializers.GroupDetailsSerializer
permission_classes = (IsAuthenticated, )
def greater(self):
return models.Group.objects.filter(shared_to=self.request.user, date_to_open__gt=timezone.now()).exists()
def get_serializer_class(self):
if self.greater():
return serializers.GroupDetailsSerializer
else:
return serializers.ClosedGroupDetailsSerializer
答案 1 :(得分:0)
您可以继续使用相同的逻辑,并使用values_list
从查询集中返回特定的值。返回的值也是一个查询集
def get_queryset(self, *args, **kwargs):
if self.greater():
return models.Group.objects.filter(shared_to=self.request.user, date_to_open__gt=timezone.now())
else:
return models.Group.objects.filter(shared_to=self.request.user, date_to_open__lt=timezone.now()).values_list('date_to_open', 'post_name' , flat = True)