字段名称选择“引用”不是有效的选择问题

时间:2019-05-14 07:00:41

标签: python django django-models django-rest-framework

我正在尝试创建一个视图集,在该视图集中我想过滤所有具有相同参考编号的记录。成员模型中有一个参考模型字段,但它告诉我这是一个无效字段。

这是视图集:

from groups.models import Member
from ..serializers import MemberSerializer
from rest_framework import viewsets

class MemberViewSet(viewsets.ModelViewSet):
    queryset = Member.objects.filter(field_name='reference')
    serializer_class = MemberSerializer

这是模型:

class Member(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    reference = models.CharField(max_length=22)
    balance = models.DecimalField(max_digits=12, decimal_places=2)
    open_tabs = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True)

这是网址:

from groups.api.views.memberViews import MemberViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'', MemberViewSet, base_name='member')
urlpatterns = router.urls

所以我想过滤掉所有具有相同参考字段值的成员对象...

2 个答案:

答案 0 :(得分:2)

如果您希望New York City; Iron Man; no superpowers Metropolis; Superman; superpowers; New York City; Spider-Man; superpowers; Gotham; Batman; no superpowers; New York City; Doctor Strange; superpowers; 在视图集中具有特定的Members,则应覆盖reference方法并将参数添加到url。

在视图集中:

get_queryset

和网址中:

from groups.models import Member
from ..serializers import MemberSerializer
from rest_framework import viewsets

class MemberViewSet(viewsets.ModelViewSet):
    serializer_class = MemberSerializer
    def get_queryset(self):
        reference = self.kwargs['reference']
        return Member.objects.filter(reference=reference)

请参阅this website

答案 1 :(得分:1)

引用QuerySet

您可以尝试使用以下方法将'SearchKey'作为您要查询的参考号吗?

queryset = Member.objects.filter(reference__contains='SearchKey')