django 有没有办法只显示一些模型字段?

suzh9iv8  于 2023-01-21  发布在  Go
关注(0)|答案(1)|浏览(116)

我有一个模型与字段示例,并有意见。我可以使,当你重定向到主页,你可以看到只有ID,标题,截止日期,完成?但当你重定向到详细信息页面,你可以看到所有的模型字段。
models.py:

class Task(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    body = models.TextField()
    deadline = models.DateTimeField()
    done = models.BooleanField()

views.py :

lass TaskList(generics.ListCreateAPIView):
    # permission_classes = (IsAuthorOrReadOnly,)
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
    # permission_classes = (IsAuthorOrReadOnly,)
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

serializers.py:

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        fields = (
            "id",
            "title",
            "body",
            "author",
            "deadline",
            "done",
        )
        model = Task

urls.py:

urlpatterns = [
    path("<int:pk>/", TaskDetail.as_view(), name="task_detail"),
    path("", TaskList.as_view(), name="task_list"),
]

请添加有用阅读材料的链接

ni65a41a

ni65a41a1#

动态修改字段:
序列化程序初始化后,可以使用. fields属性访问在序列化程序上设置的字段字典。访问和修改此属性允许动态修改序列化程序。
直接修改fields参数允许您执行一些有趣的操作,例如在运行时而不是在声明序列化程序时更改序列化程序字段的参数。
遵循上述文档中的示例:
serializers.py

class DynamicFieldsModelSerializer(serializers.ModelSerializer):
    """
    A ModelSerializer that takes an additional `fields` argument that
    controls which fields should be displayed.
    """

    def __init__(self, *args, **kwargs):
        # Don't pass the 'fields' arg up to the superclass
        fields = kwargs.pop('fields', None)

        # Instantiate the superclass normally
        super().__init__(*args, **kwargs)

        if fields is not None:
            # Drop any fields that are not specified in the `fields` argument.
            allowed = set(fields)
            existing = set(self.fields)
            for field_name in existing - allowed:
                self.fields.pop(field_name)

class TaskSerializer(DynamicFieldsModelSerializer):
    class Meta:
        fields = (
            "id",
            "title",
            "body",
            "author",
            "deadline",
            "done",
        )
        model = Task

views.py上,您可以覆盖ListCreateAPIView提供的get或ListModelMixin提供的list方法,如本示例和以下代码块所示:
views.py

class TaskList(generics.ListCreateAPIView):
    # permission_classes = (IsAuthorOrReadOnly,)
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

    def list(self, request):
        # Note the use of `get_queryset()` instead of `self.queryset`
        queryset = self.get_queryset()
        serializer = TaskSerializer(queryset, many=True, fields=('id', 'title', 'deadline'))
        return Response(serializer.data)

        
class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
    # permission_classes = (IsAuthorOrReadOnly,)
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

相关问题