Serializing Foreign Key objects in Django

后端 未结 5 893
渐次进展
渐次进展 2020-11-27 16:14

I have been working on developing some RESTful Services in Django to be used with both Flash and Android apps.

Developing the services interface has been quite simp

5条回答
  •  佛祖请我去吃肉
    2020-11-27 16:47

    Adding a newer answer to this older question: I created and recently published django-serializable-model as an easily extensible way to serialize models, managers, and querysets. When your models extend SerializableModel, they receive an overridable .serialize method that has built-in support for all relations.

    Using your example, once all of the involved models extend SerializableModel:

    joins = ['object_type', 'individual']
    artifact = Artifact.objects.select_related(*joins).get(pk=pk)
    artifact.serialize(*joins)
    

    Calling .serialize with the relations as arguments will have the library recurse over the related objects, calling .serialize on them as well. This returns a dictionary that looks like:

    {
      'id': 1,
      'year_of_origin': 2010,
      'name': 'Dummy Title',
      'notes': '',
      'object_type_id': 1,
      'individual_id': 1,
      'object_type': { ... nested object here ... },
      'individual': { ... nested object here ... }
    }
    

    You can then call json.dumps on this dictionary to transform it to JSON.

    By default, extending SerializableModel will also set the model's manager to SerializableManager (you can extend it yourself if you're using a custom manager) which uses SerializableQuerySet. This means you can call .serialize on a manager or queryset as well:

    artifacts = Artifact.objects.select_related(*joins).all()
    artifacts.serialize(*joins)
    

    This simply calls .serialize on each model object in the queryset, returning a list of dictionaries in the same format as above.

    django-serializable-model also allows you to easily override the default behavior on a per model basis, giving you the ability to do things like: add allowlists or denylists applied to each model's .serialize, always serialize certain joins (so you don't have to add them as arguments all the time), and more!

提交回复
热议问题