这是我的模型:
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
变量总是[]
。
我在这里想念什么?