在Django rest框架中的外键下拉列表中过滤结果

时间:2018-02-22 12:03:04

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

我有3个型号。用户,流程,流程图。流程模型有一个 created_by 字段,它是用户模型的外键。 processmapping模型具有 processname 字段,它是进程表的外键。

我的代码如下。

models.py

class process(models.Model):
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, db_column= "username")
    process_name = models.CharField(max_length=200)
    ....
class processmap(models.Model):
    process = models.ForeignKey(process, on_delete=models.CASCADE, db_column="process_name")
    ....

views.py

class processViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)

    queryset= process.objects.all()        
    serializer_class = processSerializer
    filter_backends = (DjangoFilterBackend,filters.SearchFilter)
    filter_fields = ('created_by', 'process_name',)


def get_queryset(self):
    if self.request.user.is_superuser:
        return self.queryset
    else:
        queryset = self.queryset
        query_set = queryset.filter(created_by=self.request.user)
        return query_set

class processmapViewset(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    try:
        queryset= processmap.objects.all()
        serializer_class = processmapSerializer
        filter_backends = (DjangoFilterBackend,filters.SearchFilter)
        filter_fields = ('process', 'service', 'sequence','process__created_by')

Serializers.py

class processSerializer(serializers.HyperlinkedModelSerializer):
#created_by = UserSerializer(many=True)
class Meta:
    model = process
    fields = ("__all__")
def perform_create(self, serializer):
    serializer.save(user=self.request.user)

class processmapSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
    model = processmap
    fields =  ("__all__")
def perform_create(self, serializer):
    serializer.save(user=self.request.user)

当用户创建进程然后转到映射进程时,外键会列出进程表中存在的所有进程。相反,我只需要列出用户登录时创建的进程。如何实现这一目标。

注意:我搜索了相同的内容并且大多数答案涉及表单。请注意我没有使用任何表单,我希望在views.py中实现该逻辑。

提前致谢:)

0 个答案:

没有答案