bartek
bartek

Reputation: 3021

django many-to-many relation not saved

here's my model:

class MediumCategory(models.Model):
    name = models.CharField(max_length=100, verbose_name=u"Nazwa")
    slug = models.SlugField(blank=True)
    parent = models.ForeignKey('self', blank=True, null=True, verbose_name=u"Rodzic")
    parameters = models.ManyToManyField(AdvertisementDescriptonParameter, blank=True)
    count_mediums = models.PositiveIntegerField(default=0)
    count_ads = models.PositiveIntegerField(default=0)

    descendants = models.ManyToManyField('self', blank=True, null=True)

    def save(self, *args, **kwargs):
        self.slug = slugify("%s_%s" % (self.id, self.name))
        super(MediumCategory, self).save(*args, **kwargs)

    def __unicode__(self):
        return unicode(self.name)

here's my admin:

class MediumCategoryAdmin(admin.ModelAdmin):
    list_display = ['name', 'parent', 'count_mediums', 'count_ads']

    def save_model(self, request, obj, form, change):
        admin.ModelAdmin.save_model(self, request, obj, form, change)
        update_category_descendants()

and here's the function:

def update_category_descendants(sender=None, **kwargs):
    data = dict()
    def children_for(category):
        return MediumCategory.objects.filter(parent=category)

    def do_update_descendants(category):
        children = children_for(category)
        descendants = list() + list(children)
        l = list([do_update_descendants(child) for child in children])
        for descendants_part in l:
            descendants += descendants_part

        if category:
            data[category] = []
            for descendant in descendants:
                data[category].append(descendant)    
        return list(descendants)

    # call it for update
    do_update_descendants(None)

    for k, v in data.iteritems():
        k.descendants = v

        print k, k.descendants.all()

what update_category_descendants does, is taking all descendands of node in the tree and saves it into descendants list of this node. Useful for browsing categorized products in store.

While print k, k.descendants.all() works as expected, in fact data is not saved in db.

when I do:

def category(request, category_slug, page=None):
    cats = MediumCategory.objects.all()

    category = MediumCategory.objects.get(slug=category_slug)
    descendants = category.descendants.all()
    print "category, descendants", category, descendants

descendants variable is always [].

What am I missing here?

Upvotes: 0

Views: 349

Answers (1)

Jeff Bradberry
Jeff Bradberry

Reputation: 1597

In your final loop in the update_category_descendants function, I believe you need to make it:

for k, v in data.iteritems():
    k.descendants.add(*v)

See also Django's related objects reference.

Upvotes: 2

Related Questions