How to Select a Record and Update It, with a Single Queryset in Django

How to select a record and update it, with a single queryset in Django?

Use the queryset object update method:

MyModel.objects.filter(pk=some_value).update(field1='some value')

Django: How do I update only ONE record in my database?

MyModel.objects.filter(pk=some_value).update(field1='some value')

The filter gets your object (returns the Queryset with only that object), then the update changes some other field that is not the PK to whatever you want.

In your case probably something like this:

context['eval_list'] = Evaluering.objects.filter(eval_relationer_id=self.kwargs.get('pk')).update(some_attribute='some value')

Django: change the value of a field for all objects in a queryset

You can update all the records in the queryset with

qs.update(active=False)

Please refer to the official Django documentation for more info

Updating several records at once using Django

Use the queryset update() method:

id_list = list_of_ids_from_checkboxes
MyModel.objects.filter(id__in=id_list).update(myattribute=True)

Your display HTML is missing a name value for the checkboxes. If you just have a single name across all checkboxes, then the list of IDs will be passed into a single POST variable, which you can get straight from request.POST (assuming you're submitting your form as a post, which you should be):

id_list = request.POST.getlist('checkboxname')

Django, update value with Queryset

The pk can not be self, it should be self.kwargs['pk']. That being said, it probably makes more sense to use a DeleteView here, and patch the delete function, like:

from django.views.generic import DeleteView
class DeleteItemView(DeleteView):

model = Item

def delete(self, request, *args, **kwargs):
self.object = self.get_object()
success_url = self.get_success_url()
self.object.status = 'C'
self.object.save()
return HttpResponseRedirect(success_url)

Note that you will need to make a POST or DELETE request in order to delete the object, so you can make a mini form for example with:

<form action={% url 'offers:delete_article' object.pk %}" method="post">
<button type="submit" class="btn btn-success" href=" title="{% trans 'Delete Item' %}"><i class="fa fa-pencil" aria-hidden="true"></i> {% trans 'Delete Item' %}</button>
</form>


Related Topics



Leave a reply



Submit