我有 3 个模型。用户、流程、流程映射。流程模型有一个created_by 字段,它是用户模型的外键。流程映射模型具有流程名称字段,它是流程表的外键。
我的代码如下。
模型.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")
....
视图.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')
序列化程序.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 中实现该逻辑。
提前致谢 :)