Django, generic relations, make fixtures
Asked Answered
M

1

8

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.com/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
Maggs answered 25/9, 2010 at 15:26 Comment(2)
Please edit question to include the relevant source. I'm not going to make the effort to click through to some other site just to see what you're talking about, and it's more difficult for someone having the same problem as you to discover this question this way.Infrastructure
You should add some detail about your problem, what exactly is the problem you have?Unmeriting
P
1

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.

  1. Refactor the if statements depending on the fields into (one or more) separate function(s).
  2. Add inspection code until you figure out what fields correspond to generic relations.
  3. Add extraction code until the generic relations are followed.
  4. 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
    
Prang answered 15/7, 2011 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.