Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Dynamically limiting queryset of related field

class PurchaseSerializer(serializers.HyperlinkedModelSerializer):
    def get_fields(self, *args, **kwargs):
        fields = super(PurchaseSerializer, self).get_fields(*args, **kwargs)
        fields['purchaser'].queryset = permitted_objects(self.context['view'].request.user, fields['purchaser'].queryset)
        return fields

    class Meta:
        model = Purchase
Comment

Dynamically limiting queryset of related field

class PurchaseList(viewsets.ModelViewSet):
    ...
    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        context = self.get_serializer_context()
        return serializer_class(*args, request_user=self.request.user, context=context, **kwargs)

class PurchaseSerializer(serializers.ModelSerializer):
    ...
    def __init__(self, *args, request_user=None, **kwargs):
        super(PurchaseSerializer, self).__init__(*args, **kwargs)
        self.fields['user'].queryset = User._default_manager.filter(pk=request_user.pk)
Comment

Dynamically limiting queryset of related field

class UserPKField(serializers.PrimaryKeyRelatedField):
    def get_queryset(self):
        user = self.context['request'].user
        queryset = User.objects.filter(...)
        return queryset

class PurchaseSeriaizer(serializers.ModelSerializer):
    users = UserPKField(many=True)

    class Meta:
        model = Purchase
        fields = ('id', 'users')
Comment

Dynamically limiting queryset of related field

from rest_framework import serializers


class LimitQuerySetSerializerFieldMixin:
    """
    Serializer mixin with a special `get_queryset()` method that lets you pass
    a callable for the queryset kwarg. This enables you to limit the queryset
    based on data or context available on the serializer at runtime.
    """

    def get_queryset(self):
        """
        Return the queryset for a related field. If the queryset is a callable,
        it will be called with one argument which is the field instance, and
        should return a queryset or model manager.
        """
        # noinspection PyUnresolvedReferences
        queryset = self.queryset
        if hasattr(queryset, '__call__'):
            queryset = queryset(self)
        if isinstance(queryset, (QuerySet, Manager)):
            # Ensure queryset is re-evaluated whenever used.
            # Note that actually a `Manager` class may also be used as the
            # queryset argument. This occurs on ModelSerializer fields,
            # as it allows us to generate a more expressive 'repr' output
            # for the field.
            # Eg: 'MyRelationship(queryset=ExampleModel.objects.all())'
            queryset = queryset.all()
        return queryset


class DynamicQuersetPrimaryKeyRelatedField(LimitQuerySetSerializerFieldMixin, serializers.PrimaryKeyRelatedField):
    """Evaluates callable queryset at runtime."""
    pass


class MyModelSerializer(serializers.ModelSerializer):
    """
    MyModel serializer with a primary key related field to 'MyRelatedModel'.
    """
    def get_my_limited_queryset(self):
        root = self.root
        if root.instance is None:
            return MyRelatedModel.objects.none()
        return root.instance.related_set.all()

    my_related_model = DynamicQuersetPrimaryKeyRelatedField(queryset=get_my_limited_queryset)

    class Meta:
        model = MyModel
Comment

Dynamically limiting queryset of related field

class PurchaseSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Purchase

    def __init__(self, *args, **kwargs):
        super(PurchaseSerializer, self).__init__(*args, **kwargs)
        if 'request' in self.context:
            self.fields['purchaser'].queryset = permitted_objects(self.context['view'].request.user, fields['purchaser'].queryset)
Comment

PREVIOUS NEXT
Code Example
Python :: printing multiple input in python 
Python :: sklearn kmeans mnist 
Python :: coin flip numpy 
Python :: Python - Cómo cruda la cuerda 
Python :: python write to file while reading 
Python :: Sending Emails 
Python :: off-by-one error in python 
Python :: boxplot python count of data 
Python :: rendere eseguibile python 
Python :: computercraft turtle place block 
Python :: sample one point from distribution python 
Python :: make a function that accepts any nuber of arguments python 
Python :: drop values in column with single frequency 
Python :: ;dslaoeidksamclsoeld,cmskadi934lglllfgl;llgldklkkkkjkklllloooofklllflll;=f]p[ 
Python :: specificity formula python 
Python :: python extract words from string with format 
Python :: wait until exe terminates python 
Python :: import nifti to numpy 
Python :: print a box like the ones below 
Python :: function continuity python 
Python :: Lists and for loops 
Python :: python zip function 
Python :: Drawing rectangle with border only in matplotlib 
Python :: numpy np sign change in df pandas zero crossing 
Python :: reload module 
Python :: how to define an empyt dic tin python 
Python :: password protected mongo server 
Python :: como escribir letras griegas en python 
Python :: check is symmetric python 
Python :: .all() python numpy 
ADD CONTENT
Topic
Content
Source link
Name
1+3 =