Categories
Python Answers

How to do bulk update with Python Django?

To do bulk update with Python Django, we can use the bulk_update method.

For instance, we write

objs = [
   Entry.objects.create(headline='Entry 1'),
   Entry.objects.create(headline='Entry 2'),
]
objs[0].headline = 'This is entry 1'
objs[1].headline = 'This is entry 2'
Entry.objects.bulk_update(objs, ['headline'])

to create 2 Entry objects and put them on the objs list.

And then we call Entry.objects.bulk_update with objs and ['headline'] to update the headline column value of each Entry entry.

Categories
Python Answers

How to fix Django object is not JSON serializable with Python Django?

To fix Django object is not JSON serializable with Python Django, we can serialize the object with Django’s built in serializers.

For instance, we write

data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")

to call serializers.serialize with 'json' and a query set to serialize the queryset into JSON.

And then we create a HttpResponse object with the serialized data and return that as the response in our view function.

Categories
Python Answers

How to compare two JSON objects with the same elements in a different order equal with Python?

To compare two JSON objects with the same elements in a different order equal with Python, we can load the JSON strings into dicts with json.loads.

Then we can sort the items with sorted and then compare them.

For instance, we write

import json

a = json.loads("""
{
    "errors": [
        {"error": "invalid", "field": "email"},
        {"error": "required", "field": "name"}
    ],
    "success": false
}
""")

b = json.loads("""
{
    "success": false,
    "errors": [
        {"error": "required", "field": "name"},
        {"error": "invalid", "field": "email"}
    ]
}
""")

def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

is_same = ordered(a) == ordered(b)

to load the JSON strings into dicts with json.loads.

And then we create the ordered function to sort the key-value pairs with the dict keys ordered.

Then we call ordered on both dicts and then check if they’re equal.

Categories
Python Answers

How to see a list of urlpatterns with Python Django?

Sometimes, we want tto see a list of urlpatterns with Python Django.

In this article, we’ll look at how to see a list of urlpatterns with Python Django.

How to see a list of urlpatterns with Python Django?

To see a list of urlpatterns with Python Django, we can install the django-extensions package.

To install it, we run

pip install django-extensions

Then we add it to INSTALLED_APPS in settings.py with

INSTALLED_APPS = (
#...
'django_extensions',
#...
)

Then we run

python manage.py show_urls

to show a list of all the URLs on the screen.

Conclusion

To see a list of urlpatterns with Python Django, we can install the django-extensions package.

Categories
Python Answers

How to serialize many to many field with Python Django rest framework?

Sometimes, we want to serialize many to many field with Python Django rest framework.

In this article, we’ll look at how to serialize many to many field with Python Django rest framework.

How to serialize many to many field with Python Django rest framework?

To serialize many to many field with Python Django rest framework, we can add a serializer with many set to True.

For instance, we write

class PostSerializer(serializers.ModelSerializer):
    tag = TagSerializer(read_only=True, many=True)

    class Meta:
        model = Post
        fields = ('tag', 'text',)

to create the PostSerializer with the tag field assigned to the TagSerializer instance.

We set many to true to let us serialize many to many fields.

Conclusion

To serialize many to many field with Python Django rest framework, we can add a serializer with many set to True.