Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework access item by lookup field instead of pk 3.4 DRF

I need to have lookup field in order my frontend sends email which should be deleted but I get item not found. I've researched a lot about this problem but I can't figure out which DRF version what supports.

class EmailReminderSerializer(serializers.ModelSerializer):
    city = serializers.CharField(max_length=255)
    url = serializers.HyperlinkedIdentityField(
        view_name='web:email_reminder-detail',
    )

    class Meta:
        model = EmailReminder
        fields = '__all__'
        extra_kwargs = {
            'url': {'lookup_field': 'email'}
        }

Now I have url but it points to instance pk, not by my desired lookup field. Any suggestions of how it works in 3.4 version or do you have any other solutions to some lower version >=3.0?

like image 404
aleks Avatar asked Oct 12 '16 07:10

aleks


People also ask

What is the use of REST framework in Django?

Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around over the Django Framework. There are three stages before creating an API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.

What is the difference between DRF and search in Django?

The Django REST framework provides search functionality out of the box. search specifies the pattern that needs to be matched. search_fields specify the database columns against which the pattern needs to be matched. DRF default behavior works with static search_fields.

What is filter API in Django?

API Guide 1 DjangoFilterBackend. The django-filter library includes a DjangoFilterBackend class which supports highly customizable field filtering for REST framework. 2 SearchFilter. The SearchFilter class supports simple single query parameter based searching, and is based on the Django admin's search functionality. 3 OrderingFilter. ...

How to search full word search in Django REST framework?

Django REST framework full word search filter The djangorestframework-word-filter developed as alternative to filters.SearchFilter which will search full word in text, or exact match.


2 Answers

Oh okay, I got it. For serialized models you only need lookup_field in your view but for hyperlinked serialized models you need extra_kwargs in serializers plus lookup field in views. Hope it helps someone

like image 84
aleks Avatar answered Nov 15 '22 15:11

aleks


You should modify the lookup field in your view instead. As shown in DRF docs, you can do the following.

in views.py

from rest_framework import viewsets

class EmailReminderViewSet(viewsets.ModelViewSet):
    serializer_class = TagSerializer
    lookup_field = 'email'
like image 20
ahmohamed Avatar answered Nov 15 '22 16:11

ahmohamed