logo
down
shadow

Bulk, partial updates with Django Rest Framework


Bulk, partial updates with Django Rest Framework

Content Index :

Bulk, partial updates with Django Rest Framework
Tag : django , By : Jack
Date : November 28 2020, 08:01 AM

fixed the issue. Will look into that further After ~10 hours banging my head against this wall, I decided that the right way could take a back seat and I'd make do with the hack way that works. I added the following gnarlfest to my viewset.
@action(methods=['patch'], detail=False)
def bulk_update(self, request):

    data = {  # we need to separate out the id from the data
        i['id']: {k: v for k, v in i.items() if k != 'id'}
        for i in request.data
    }

    for inst in self.get_queryset().filter(id__in=data.keys()):
        serializer = self.get_serializer(inst, data=data[inst.id], partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()

    return Response({})

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Django Rest Framework bulk updates inserting instead of updating


Tag : django , By : Pip
Date : March 29 2020, 07:55 AM
help you fix your problem You're not passing object instances to your serializer. (Thus it will create new instances rather than update.) See the docs on dealing with multiple objects in serializers where you'll see your QuerySet passed in.

Django REST Framework partial updates with depth


Tag : python , By : Diego
Date : March 29 2020, 07:55 AM
I wish did fix the issue. This was originally answered in the question, but I feel it deserves a decent explanation.
In Django REST Framework 3, the process of saving nested data has been made considerably more clear. Now you can override update on the serializer and manipulate the validated_data, updating your model objects manually. This is specifically documented now, but the implementation is typically very specific to the situation.
class Users(models.Model):
    user = models.OneToOneField(User)
    foo = models.CharField()
    baz = models.CharField()
    yin = models.CharField()
    yang = models.CharField()

    def save(self, *args, **kwargs):
        user_ = self.user
        user_.save(update_fields=('username', 'first_name', 'last_name'), **kwargs)

        return super(Users, self).save(*args, **kwargs)

Trying to bulk upload to django-rest-framework (ModelViewSets) using django.client


Tag : python , By : kangfoo2
Date : March 29 2020, 07:55 AM
wish of those help Yeah, Bulk uploading is possible in django rest framework.
You can use Django REST Framework Bulk.
BulkListSerializer,
BulkSerializerMixin,
ListBulkCreateUpdateDestroyAPIView,
class Meta(object):
    model = FooModel
    # only necessary in DRF3
    list_serializer_class = BulkListSerializer

In the Django REST framework, how to allow partial updates when using a ModeViewSet?


Tag : python , By : nonkelhans
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You don't need to adapt the serializer in any way. With that viewset, any call to the "detail" endpoint using the PATCH method will do a partial update.
The Django Rest Framework ModelViewSet base class includes the following mixin. Here you can see how partial=True is passed when calling partial_update, which is routed to the PATCH method by default:
class UpdateModelMixin(object):
    """
    Update a model instance.
    """
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # refresh the instance from the database.
            instance = self.get_object()
            serializer = self.get_serializer(instance)

        return Response(serializer.data)

    def perform_update(self, serializer):
        serializer.save()

    def partial_update(self, request, *args, **kwargs):
        kwargs['partial'] = True
        return self.update(request, *args, **kwargs)

Django rest framework bulk: Correct URL syntax for bulk operations?


Tag : django , By : Steven Weber
Date : October 07 2020, 03:00 PM
wish help you to fix your issue I'm attempting to carry out bulk DELETEs/PUTs on my Django API, mymodel inherits from MultipleDBModelViewSet which in turn inherits from the BulkModelViewSet , There are two things they are saying at their documentation.
url(r'foo/', ...)
url(r'foo/(?P<pk>\d+)/', ...)
class FooView(BulkDestroyAPIView):
    def allow_bulk_destroy(self, qs, filtered):
        # custom logic here
        # default checks if the qs was filtered
        # qs comes from self.get_queryset()
        # filtered comes from self.filter_queryset(qs)
        return qs is not filtered
class SimpleViewSet(generics.BulkModelViewSet):
    def filter_queryset(self, queryset):
        ids = self.request.query_params.get('ids')
        if ids:
            return queryset.filter(id__in=ids.split(',')
        # returns normal query set if no param
        return queryset
Related Posts Related QUESTIONS :
  • Django Admin - Upload multiple images to multiple model objects in a single upload
  • Wagtail PASSWORD_REQUIRED_TEMPLATE is not overriding the default login
  • get checkbox items list from table in django without using django-forms
  • Django Running Particular Test
  • How do I display output of a python within Html in django?
  • How can I capture errors and exceptions data from frontend response to django to add more context
  • Django generate group by different than id
  • populate table with initial data
  • Django (admin.e104) must inherit from 'InlineModelAdmin'
  • how to display a html file stored in s3 in aws in my django template?
  • Django: AttributeError: type object 'GroupModel' has no attribute '_meta'
  • SQLite objects created in a thread can only be used in that same thread with Django 2.2.2 and ipdb
  • Django - query filter on manytomany is exists
  • Django REST Framework: URLs without PK
  • How to access a Postgres database from a python program without django or heroku
  • When trying set corsheaders in settings.py file
  • 400(Bad request) status code when making request with axios in reactjs
  • ERR_CONNECTION_REFUSED with Django and Vue.js bundle files
  • LDAP Authentication not working in Graphite
  • send value from anchor tag to views
  • The views didn't return an HttpResponse object. It returned None instead
  • Sum of related objects across 2 FK to the same table, with conditions
  • Queryset Django - according to parameters date in weight compartment
  • how to convert Django 2.0 url() to path()
  • Signal/Method for every executed sql statement
  • How to sum django model fields
  • django template styntex {% if p.category == "help" %} {% endif %} is not work
  • NGINX 502 bad gateway gunicorn timeout
  • How to pass a variable from a template to a view in Django
  • How to force redirect_uri to use HTTPS with python-social-app?
  • How to restrict Django models from using certain foreign key values?
  • Product items is not iterable from models
  • Removing items from celery_beat doesn't remove them from database schedule
  • Column field is not recognized/not defined
  • AttributeError at has no attribute 'objects'
  • how to Validate Expire date is bigger than start date in Django Model Form
  • Django Application
  • How to get my Django app in a real server?
  • How do I run a unit test against the production database?
  • How to browse (no text editor) .rst files?
  • Filter Queryset in Django inlineformset_factory
  • IPN delivery failed. HTTP error code 403: Forbidden
  • integrating django-paypal
  • Django equivalent for latest entry for each user
  • Writing custom Django form fields and widgets
  • Django queryset to find a char value with filtered out spaces?
  • Django i18n: how to not translate the admin site?
  • apache virtual host to work with django
  • Using django-piston, how can I write out HTTP headers in the response?
  • Error in django url.py?
  • Django: getting the list of related records for a list of objects
  • Edit/show Primary Key in Django Admin
  • How do I list all available context variables?
  • Treebeard admin in Django
  • Django and Secure iCalendar Feed
  • Syncing data between devel/live databases in Django
  • What custom themes are there for Django Admin?
  • ChoiceField or CharField in django form
  • Django and ImageField Question
  • Django crash without message
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com