How to run a filter over the property of my Django Model?
I am working with a Model has a payload
property which contains a Base64 encoded JSON.
I am writing admin views which will consolidate data represented by this m开发者_运维知识库odel and several others.
- I want to display the Base64 decoded version of the JSON in
ModelAdmin
views. - I also want to run a query which would return rows such that a specific element in the decoded JSON matches a value.
Is this doable in Django ?
You have to create a custom admin template with the following code:
{% extends "admin/change_form.html" %}
{% load i18n %}
{% block content %}
This is the field: {{ original.payload }}
{{ block.super }}
{% endblock %}
save it as, say, "templates/admin/change_model_payload.html" and add this to the model's ModelAdmin:
change_form_template = "admin/change_model_payload.html"
For #2, you might want to create a custom template tag to retrive the DB entries.
If you expect a specific element of a specific type, then you'd better decode it on save() than to blindly store it in base64.
- There is no easy way to get info from base64-encoded data.
- base64 does not align on bytes boundaries, so you can't look at the encoded data and say "ah, there starts the property xxx!"
- json should already have its binary data encoded in base64, so you shouldn't encode it again in base64.
My advice is to create a PayloadData class with all the expected attributes, with a one-to-one to your original model, where you store the attributes upon save()ing the payload, and where you can index, query, filter, order, join and any other interesting things a RDBMS allows you to do.
OR ditch you database and Django's own ORM and go no-sql. Most document-based nosql servers have the ability to query (or at least create views) for any kind of subfield condition.
精彩评论