Olivier H
Olivier H

Reputation: 898

Django deserializer, with fields set as serialize=False

[edit: using django-1.1.1]

Hello,

I'm using django classes that store a blob (a string b64 encoded more exactly) corresponding to an icon for the object.

I serialize the objects as json to communicate with the different front-end clients.

I don't want to expose the pure icon blob in the json result (but serve it as image under a certain url), so my icon field is defined as thus :

icon = models.TextField(null=True, serialize=False)

But when time comes to save my object, I lose my icon, because, obviously, the value is not set by the incoming json dictionnary.

I'd like to write written a hack like so :

class MyIconizedClass(models.Model):
    def __init__(self, *args, **kwargs):
        if self.pk is not None and self._icon is None:
            old_self = MyIconizedClass.object.get(pk=self.pk)
            self.icon = old.self.icon

Not very satisfied with this because it would query in DB every time, plus, it will recurse indefinitely if the icon is effectively None.

Another way would be to rewrite the deserializer.

Is there any workaround, using django's internal mechanisms?

Upvotes: 1

Views: 907

Answers (2)

Olivier H
Olivier H

Reputation: 898

I changed my model so as to be less query-greedy.

class MyIconizedClass(models.Model):
    ...
    ...


class IconClass(models.Model):
    obj = models.ForeignKey(MyIconizedClass)
    blob = models.TextField()

I only query the IconClass table on demand, when working with certain url entrypoints such as

  • GET /iconized/42/icon
  • PUT /iconized/42/icon
  • DELETE /iconized/42/icon

When accessing the object itself, I don't need to know of icons (GET /iconized/42).

Upvotes: 0

Andrey Fedoseev
Andrey Fedoseev

Reputation: 5382

Try this:

for deserialized_object in serializers.deserialize("json", data):
    try:
        existing_object = MyIconizedClass.objects.get(pk=deserialized_object.pk)
        deserialized_object.icon = existing_object.icon
    except MyIconizedClass.DoesNotExist:
        pass     
    deserialized_object.save()

It also queries the database but it won't cause any recursion.

Upvotes: 1

Related Questions