Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In my opinion the cleanest place for the code you need is as a new Manager method (eg from_json_string) on a custom manager for the NinjaData model.</p> <p>I don't think you should override the standard create, get_or_create etc methods since you're doing something a bit different from what they normally do and it's good to keep them working normally.</p> <p><strong>Update:</strong> I realised I'd probably want this for myself at some point so I have coded up and lightly tested a generic function. Since it recursively goes through and affects other models I'm no longer certain it belongs as a Manager method and should probably be a stand-alone helper function.</p> <pre><code>def create_or_update_and_get(model_class, data): get_or_create_kwargs = { model_class._meta.pk.name: data.pop(model_class._meta.pk.name) } try: # get instance = model_class.objects.get(**get_or_create_kwargs) except model_class.DoesNotExist: # create instance = model_class(**get_or_create_kwargs) # update (or finish creating) for key,value in data.items(): field = model_class._meta.get_field(key) if not field: continue if isinstance(field, models.ManyToManyField): # can't add m2m until parent is saved continue elif isinstance(field, models.ForeignKey) and hasattr(value, 'items'): rel_instance = create_or_update_and_get(field.rel.to, value) setattr(instance, key, rel_instance) else: setattr(instance, key, value) instance.save() # now add the m2m relations for field in model_class._meta.many_to_many: if field.name in data and hasattr(data[field.name], 'append'): for obj in data[field.name]: rel_instance = create_or_update_and_get(field.rel.to, obj) getattr(instance, field.name).add(rel_instance) return instance # for example: from django.utils.simplejson import simplejson as json data = json.loads(ninja_json) ninja = create_or_update_and_get(NinjaData, data) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload