Created
October 27, 2013 13:57
-
-
Save Starou/7182446 to your computer and use it in GitHub Desktop.
A Django admin action to create fixtures from database.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from django.db import models | |
from django.contrib import admin | |
from django.core import serializers | |
from django.http import HttpResponse | |
class ModelAdmin(admin.ModelAdmin): | |
actions = ["dumpdata"] | |
def get_actions(self, request): | |
actions = super(ModelAdmin, self).get_actions(request) | |
if not request.user.is_superuser and "dumpdata" in actions: | |
del actions["dumpdata"] | |
return actions | |
def dumpdata(self, request, queryset): | |
json = {} | |
format = "json" | |
indent = 2 | |
use_natural_keys = True | |
objects = list(queryset) | |
dependancies = [] | |
for obj in queryset: | |
append_obj_dependancies(obj, dependancies) | |
objects = dependancies + objects | |
#TODO sort object by appname.modelname. | |
# use_natural_keys fout la merde dans les dossiers pour les ref user. | |
stream = serializers.serialize(format, objects, indent=indent, | |
use_natural_keys=use_natural_keys) | |
return HttpResponse(stream, mimetype='application/json') | |
dumpdata.short_description = u'Dump the selected objects' | |
def append_obj_dependancies(obj, dependancies, add_m2m=True): | |
for field in obj.__class__._meta.fields: | |
if isinstance(field, models.ForeignKey): | |
rel = getattr(obj, field.name) | |
if rel and rel not in dependancies: | |
dependancies.insert(0, rel) | |
append_obj_dependancies(rel, dependancies, add_m2m=False) | |
if add_m2m: | |
for related in obj._meta.get_all_related_objects(): | |
try: | |
objs = getattr(obj, related.get_accessor_name()).all() | |
# Cas des OneToOne. | |
except AttributeError: | |
objs = [getattr(obj, related.field.related_query_name())] | |
for rel in objs: | |
dependancies.insert(0, rel) | |
append_obj_dependancies(rel, dependancies, add_m2m=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment