django多对多关系没有保存

时间:2012-07-28 09:35:13

标签: django 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)

这是我的管理员:

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()

这是函数:

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()

update_category_descendants所做的是将树中节点的所有后代保存到此节点的descendants列表中。用于浏览商店中的分类产品。

虽然print k, k.descendants.all()按预期工作,但实际上数据不会保存在db。

当我这样做时:

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变量始终为[]

我在这里缺少什么?

1 个答案:

答案 0 :(得分:2)

update_category_descendants函数的最后一个循环中,我相信你需要做到:

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

另见Django's related objects reference