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

标签 django django-models django-rest-framework django-views

我在 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/

相关文章:

django - many=True TypeError 对象不可迭代

python - 尝试使用 django.client 批量上传到 django-rest-framework (ModelViewSets)

python - DRF 序列化程序更新嵌套用户

python - Django 和 python - 使用变量值作为模型名称

python - 无法解析余数 : '==0' from 'data.tab_nid==0'

python - 无法使用 models.Manager 检索 Django 对象列表

python - 在没有标点符号或空格的 Django 模型中查找匹配项

javascript - 通过ajax从django查询集中填充下拉列表

django - 从 Django 模型中的选择中获取人类可读名称的实际值

python - Django 模型中的 ModelFields 是如何分配的?