yatharth meena
yatharth meena

Reputation: 388

How to change lookup field in Model.viewset to other unique parameter in Django Rest Framework?

I'm using Modelviewset in a django-rest-framework project. I want to change the lookup field to email(unique) instead of using id.

So I tried adding lookup_field = 'email' inside my Schema Viewset but it is not working, and this is what I'm getting:

{
    "detail": "Not found."
}

How do I resolve this?

views.py

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

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

models.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

serializers.py

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

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

The below image shows what I want but with email and not using id:

Upvotes: 7

Views: 10265

Answers (3)

birnenpfluecker
birnenpfluecker

Reputation: 41

For me it is even working, when I am not setting the lookup_field in the Meta class of the serializer.

So try out only setting the lookup_field in your viewset. That might be enough.

Upvotes: 0

Dean Christian Armada
Dean Christian Armada

Reputation: 7374

For me I only needed to update the ViewSet. No need to update the Serializer

class SchemaViewSet(viewsets.ModelViewSet):
    queryset = models.Schema.objects.all()
    serializer_class = serializers.SchemaSerializer
    lookup_field = "email"

Upvotes: 3

Sumeet Kumar
Sumeet Kumar

Reputation: 1019

Update your code as follow:

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 = "[^/]+"  

Upvotes: 13

Related Questions