gpt4 book ai didi

django - 如何将 Model.viewset 中的查找字段更改为 Django Rest Framework 中的其他唯一参数?

转载 作者:行者123 更新时间:2023-12-04 02:36:46 29 4
gpt4 key购买 nike

我在 django rest 框架中使用 Modelviewset。我想将查找字段更改为电子邮件(唯一)而不是 id。我试过添加lookup_field = 'email'在我的架构 View 集中,但它不起作用。这就是我得到的
{
"detail": "Not found."
}
我该如何解决这个问题。

我的 Views.py:

class SchemaViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):

queryset = models.Schema.objects.all()
serializer_class = serializers.SchemaSerializer
lookup_field = 'email'

我的模型.py:
class Schema(models.Model):
"""Database model for Schema """

name= models.TextField()
version = models.TextField()
email = models.EmailField(unique = True )


def __str__(self):
return self.email

我的序列化程序.py:
class SchemaSerializer(serializers.ModelSerializer):
"""Serializes Schema"""

class Meta:
model = models.Schema
fields = ( 'id', 'name', 'version', 'email')

enter image description here
enter image description here

This is what i want but instead from mail id

最佳答案

更新您的代码如下:

class SchemaSerializer(serializers.ModelSerializer):
"""Serializes Schema"""

class Meta:
model = models.Schema
fields = ("id", "email")
lookup_field = "email"


class SchemaViewSet(viewsets.ModelViewSet):
queryset = models.Schema.objects.all()
serializer_class = serializers.SchemaSerializer
lookup_field = "email"
lookup_value_regex = "[^/]+"

关于django - 如何将 Model.viewset 中的查找字段更改为 Django Rest Framework 中的其他唯一参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61452449/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com