I'm trying to add generic relations and one-to-one relations support for django-test-utils makefixture command, here is the source http://github.co开发者_如何学Cm/ericholscher/django-test-utils/blob/master/test_utils/management/commands/makefixture.py
Does somebody have ideas how to do this? Or may be there is another tool for such thing as:
./manage.py dumpcmd User[:10] > fixtures.json
You have several options how to approach the problem. I'll concentrate on the poke-the-code aproach, since it's been a while since I mucked around with django internals.
I have included the relevant code below from the link. Note that I have removed irrelevant parts. Also note that the part you'll be editing YOUR CASE HERE is in need of a refactor.
Follow the following algorithm until you're satisfied.
- Refactor the
if
statements depending on the fields into (one or more) separate function(s). - Add inspection code until you figure out what fields correspond to generic relations.
- Add extraction code until the generic relations are followed.
Test.
def handle_models(self, models, **options): # SNIP handle options all = objects if propagate: collected = set([(x.__class__, x.pk) for x in all]) while objects: related = [] for x in objects: if DEBUG: print "Adding %s[%s]" % (model_name(x), x.pk) # follow forward relation fields for f in x.__class__._meta.fields + x.__class__._meta.many_to_many: # YOU CASE HERE if isinstance(f, ForeignKey): new = getattr(x, f.name) # instantiate object if new and not (new.__class__, new.pk) in collected: collected.add((new.__class__, new.pk)) related.append(new) if isinstance(f, ManyToManyField): for new in getattr(x, f.name).all(): if new and not (new.__class__, new.pk) in collected: collected.add((new.__class__, new.pk)) related.append(new) # SNIP objects = related all.extend(objects) # SNIP serialization
精彩评论