drf Flashcards

1
Q

what a router does is

A

generates the url patterns for the viewsets you register to it, and gives you an object to throw into urls.py

goes in stub folder
project_name/project_name/router.py

from rest_framework import routers
from app_name.api.viewsets import *

router = routers.DefaultRouter()
router.register(r’model_name’, RatingViewSet, ‘model_name’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

a viewset is

A

a class in which you define the actions and serializers you want to use, or use ModelViewSet to just set the serializer and and queryset and all the functions from the router will be injected.

note: when setting the queryset, dont use an underscore query_set.

in app_name/api/viewsets.py

from app_name.models import ModelName
from .serializers import ModelnameSerializer
from rest_framework import viewsets
from rest_framework import permissions

class ModelNameViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    queryset = Modelname.objects.all()
    serializer_class = ModelNameSerializer
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

to use request.user in the viewset, type

A

Overwrite the queryset property with a custom function

class ModelNameViewSet(viewsets.ModelViewSet):
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    serializer_class = ModelNameSerializer
    def get_queryset(self):
        user = self.request.user
        return ModelName.objects.filter(user=user)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

a serializer is

A

a class that defines how to convert an object to a key, value dictionary. It’s a lot like a form, and can perform validations

class ModelNameSerializer(serializers.Serializer):
    field_1 = serializers.EmailField(required=False)#makes optional
    field_2 = serializers.CharField(max_length=200)
    def validate_field_1(self, field_value):
        if field_value < 1:
            raise serializers.ValidationError("string")
        return field_value

or to skip the field definitions and use the defaults from the model

from rest_framework import serializers
from app_name.models import ModelName

class ModelNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelName
        fields = ('field_1', 'field_2',) # or just "\_\_all\_\_"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

To add a custom computed field to a serializer

A

add a function to your model

then add to serializer

class ModelNameSerializer(serializers.Serializer):
    new_function = serializers.ReadOnlyField()
    class Meta:
        model = ModelName
        fields = ('new_function',)

or maybe for foreign keys

class ModelNameSerializer(serializers.ModelSerializer):
    custom_field = serializers.ReadOnlyField(source="foreign_key_field.field")
    class Meta:
        model = ModelName
        fields = ('field_1', 'custom_field',)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

good tutorial

A

https://www.youtube.com/watch?v=riZYgLOYq4g&t=562s

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

to have nested objects inside a serializer

A

https://stackoverflow.com/questions/14938895/serializer-dealing-with-nested-objects

and to have them nested but with a reverse relationship list of objects
https://stackoverflow.com/questions/14573102/how-do-i-include-related-model-fields-using-django-rest-framework

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

to create a serializer that loads in related objects (that have a forward relationship, aka, they contain the field=models.ForeignKey()) as nested dictionaries, type

A
class ModelNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelName
        depth = 1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

to serialize a related foreign key object

A

name the field in the serializer the same as the foreign key field name, and set the value to the serializer you want to use for the related element.

class RelatedModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = RelatedModel
        fields = ('field_1', 'field_2')
class ProductSerializer(serializers.ModelSerializer):
    related_field_name = RelatedModelSerializer()
    class Meta:
        model = Product
        fields = ('field_1', 'field_2', 'related_field_name')
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

notes

A

from rest_framework import routers
from noot.api.viewsets import *

router = routers.DefaultRouter()
# router.register(r'ratings', RatingViewSet, 'ratings')
# this generates a list of url() pattern objects and passes them into the urls.py (just creates /object_name/ and /object_name/id/ because the actions are chosen with http method)
# the first argument is the prefix of the url pattern definition/namespace
# The router uses the queryset defined in the viewset to determine the base_name 
# base_name is the prefix it will use for names in the url(..., name='string') definitions. Becomes url(..., name='prefix_base_name_string')
# rest of the name will be the filled with the generated view types: base_name-list, base_name-detail from the viewset
# using a routers prevents you from needing to write your own url patterns
# https://stackoverflow.com/questions/46053922/delete-method-on-django-rest-framework-modelviewset
# To hit the different actions, you need to use the right http method. list:get, create:post, retrieve:get, update:put, partial_update:patch, destroy:delete.
# router makes these automatically
url(r'^api/', include(router.urls)), # this allows you to add additional urls by registering them to router

from rest_framework import serializers
from noot.models import Rating

# class RatingSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Rating
#         fields = ('noot', 'rating', 'user', 'pk')
from noot.models import Rating
# from .serializers import RatingSerializer
from rest_framework import viewsets
# class RatingViewSet(viewsets.ModelViewSet):
#     queryset = Rating.objects.all()
#     serializer_class = RatingSerializer
# the attributes set in this ModelView class are just there to be used by all the later functions
# many of these functions are invisible because they are inherited from parent class
# if you use a modelviewset instead of viewset, it adds the methods the router generated routes for: list, create, retrieve, update, partial_update, delete
# otherwise you need to define these functions yourself
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

To serialize a qs and have a nested field thats a reverse relationship

A
class ModelNameSerializer(serializers.ModelSerializer):
    model_name_set = ReverseRelatedModelNameSerializer(read_only=True, many=True, source='model_name_set')
    class Meta:
        model = Cart
        depth = 1
        fields = (
            'field_1', 
            'field_2', 
            'model_name_set', 
        )
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

To make a user pass a test or otherwise redirect for function based views

A

https://stackoverflow.com/questions/8082670/django-user-passes-test-decorator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

To create custom rest framework permission

A

https://www.youtube.com/watch?v=-0c88d24qzM

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

To add a function decorator to a class based views methods

A

https://stackoverflow.com/questions/8082670/django-user-passes-test-decorator

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

under the hood, the generated code for the list function in a viewset is

A
def list(self, request);
    queryset = ModelName.objects.all()
    serializer = ModelNameSerializer(queryset, many=True)
    return Response(serializer.data)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

to make a custom view in a modelviewset, type

A
Note: This assumes I already set the queryset and serializer on the class
@action(methods=["GET"], detail=False) #this means dont listen of the detail url
def newest(self, request):
    newest = self.get_queryset().first()
    serializer = self.get_serializer_class()(newest)
    return Response(serializer.data)
17
Q

detail=True in a custom view inside a viewset is for

A

telling it to listen to requests on the detail url or the list url

ie item/ or item/1/

seems that self.get_object() on an action with detail=True inserts the url id ad the id filter on the queryset.

@action(detail=True, methods=['post'])
def set_password(self, request, pk=None):
    user = self.get_object()
    serializer = PasswordSerializer(data=request.data)
    if serializer.is_valid():
        user.set_password(serializer.data['password'])
        user.save()
        return Response({'status': 'password set'})
    else:
        return Response(serializer.errors,
                        status=status.HTTP_400_BAD_REQUEST)
18
Q

to add a custom permission to a custom view in a viewset, type

A

@action(detail=False, methods=[‘post’], permission_classes=[IsAdminOrIsSelf])

19
Q

To make objects only edittable by their owners you need to

A

create a custom permission like this.

https://stackoverflow.com/questions/50646966/django-rest-framework-related-model-permissions

20
Q

js: To import a member export and default export in the same line, type

A

import DefaultExport, { MemberExport } from ‘package’;

21
Q

vscode: To format the document, type

A

command + shift + p
type format
enter

22
Q

to validate two fields are unique together, type

A
class Show(models.Model):
   day = models.ForeignKey(TimeTable, related_name='show')
   time = models.TimeField(choices=CHOICE_TIME)
   movie = models.ForeignKey(Movie)
class Meta:
    unique_together = ('day', 'time')
23
Q

To filter in a viewset without overwriting def get_queryset(self), use

A

pip install django-filter, installed apps ‘django_filters’

http://url.com?ordering=-field_1,field_2,field_1&field_3=True

add to ViewSet

filter_backends
= (django_filters.rest_framework.DjangoFilterBackend, )
filter_fields = (‘field_1’, ‘field_2’) #allowed filter get params
search_fields = (‘field_1’,) #uses partial match on all fields
ordering_fields = (‘field_1’, ‘field_2’) #allowed sort fields
ordering = (‘field_1’,) #optional default ordering

or

from django_filters import rest_framework as filters

class ModelNameFilter(filters.FilterSet):
    field_1 = filters.NumberFilter(field_name='models_field_name', lookup_expr='gte')
    max_price = filters.NumberFilter(field_name='models_field_name', lookup_expr='lte')
    start_date = filters.DateFilter(field_name='date', lookup_expr='lt')
    end_date = filters.DateFilter(field_name='date_joined', lookup_expr='gt')
    class Meta:
        model = ModelName
        fields = ['field_1', 'field_2', 'min_price', 'max_price']

add to viewset
filter_class = ModelNameFilter

https://stackoverflow.com/questions/47220070/django-rest-framework-filtering-by-datetime

24
Q

A filter class is

A

a class that defines the permitted get parameters that will return filtered querysets.

import django_filters

class ModelNameFilter(django_filters.FilterSet):
    class Meta:
        model = ModelName
        fields = {
            'field_1': ['icontains'],
            'field_2': ['icontains'] 
        }

https://www.youtube.com/watch?v=nle3u6Ww6Xk&t=215s

25
Q

The most basic example of DRF is

A

from rest_framework import routers, viewsets, serializers
from debate.models import ModelName

class ModelNameSerializer(serializers.ModelSerializer):
    class Meta:
        fields = "\_\_all\_\_"
        model = ModelName
class ModelNameViewSet(viewsets.ModelViewSet):
    queryset = ModelName.objects.all()
    serializer_class = ModelNameSerializer

router = routers.DefaultRouter()
router.register(model_name’, ModelNameViewSet)

urlpatterns = [
url(r’^api-auth/’, include(‘rest_framework.urls’)),
url(r’^api/’, include(router.urls)),
]

26
Q

to get great python features, learn this.

A

https://www.youtube.com/watch?v=CZ8bZPqtwU0&index=2&list=PLP8GkvaIxJP0VAXF3USi9U4JnpxUvQXHx