ShinySides
ShinySides

Reputation: 428

Serialize Class Django

I'm trying to serialize a class in Django, so that I can get all the available fields on a json file, I would need something like

{"tablename": ["Verbose Name", "ModelType", "RelatedClass", "relatefield"]}

The idea is that most of the objects will only have the verbose name and the model type, but for related fields, it will also have the name of the class that the relation refers to, and a field that I can add manually say on helptext as a default, or I can just leave that out probably and work on it differently.

I need to do this to the class not to the object I've tried with pickle and jsonpickle but they don't seem to work as I was expecting, I'm out of ideas, any input would be greatly appreciated.

Thanks.

Edit: Need to clarify better

class Test(models.Model):
    name = models.CharField(verbose_name="Name")
    email = models.CharField()
    books = models.ForeignKey(Book, verbose_name="Books")

class Book(models.Model):
    name = models.CharField()

now I just want to serialize Test, no value has to be in it at all, just the class itself, so you'd have.

"name": {"verbose_name": "Name", "type": "CharField"}
"books": {"verbose_name": "Books", "type": "ForeignKey", "related_class": "Book", "related_class": "Country", "related_field": "name"}

I need a json around them lines to come out, but I wont have to run any queries with data in them just model information.

Upvotes: 0

Views: 972

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Classes are objects, model fields too, so you can easily inspect them. One solution would be to write your custom json encoder for model classes (not instances). All informations about the model fields, verbose name etc are stored in YourModelClass.__meta.

Upvotes: 1

ndpu
ndpu

Reputation: 22561

Django’s serialization framework provides a mechanism for “translating” Django models into other formats. Usually these other formats will be text-based and used for sending Django data over a wire, but it’s possible for a serializer to handle any format (text-based or not).

from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())

xml example:

<?xml version="1.0" encoding="utf-8"?>
<django-objects version="1.0">
    <object pk="123" model="sessions.session">
        <field type="DateTimeField" name="expire_date">2013-01-16T08:16:59.844560+00:00</field>
        <!-- ... -->
    </object>
</django-objects>

json:

[
    {
        "pk": "4b678b301dfd8a4e0dad910de3ae245b",
        "model": "sessions.session",
        "fields": {
            "expire_date": "2013-01-16T08:16:59.844Z",
            ...
        }
    }
]

Deserializing data is also a fairly simple operation:

for obj in serializers.deserialize("xml", data):
    do_something_with(obj)

https://docs.djangoproject.com/en/dev/topics/serialization/

Upvotes: 1

Related Questions