Django在自引用ManyToManyField中获取相关项目

时间:2014-12-23 12:02:35

标签: python django sorting django-orm

如何通过自引用ManyToManyField获取与零件关联的所有项目?如何修复我的观点以使 part_list 包含与'product'关联的所有部分的列表以及order_by指定的顺序?

# views.py

def productdetail(request, slug):    
    product = get_object_or_404(PartModel, slug=slug)

    part_list = PartModel.objects.all().filter(buildpart__id=product.pk).order_by('family__type')

    return render(request, 'productdetail.html', locals())

这是模板:

# productdetail.html

    <header>
        <h1>'{{ product.name }}' Detail Page</h1>
    </header>

    <p>{{ product.name }}
    <p>{{ product.slug }}
    <p>{{ product.family }}
    <p>{{ product.family.type }}
    <p>{{ product.family.make }}
    <p>${{ product.price }}
    {% for part in part_items %}
        <p>{{ part.name }}
    {% endfor %}

注意PartModel模型通过buildpart字段保存我们的库存及其自引用的BuildPart ManyToMany模型:

class PartModel(models.Model):
    family = models.ForeignKey(PartFamily)
    name = models.CharField("Model Name", max_length=50, unique=True)
    buildpart = models.ManyToManyField('self', through='BuildPart',
                                symmetrical=False, related_name='+')

class Build(models.Model):
    build = models.ForeignKey(PartModel, related_name='+')
    part = models.ForeignKey(PartModel, related_name='+')
    quantity = models.PositiveSmallIntegerField(default=1)

    class Meta:
        abstract = True
        unique_together = ('build', 'part')

    def __unicode__(self):
        return self.build.name + ' with ' + str(self.quantity) + ' * ' + \
               self.part.family.make.name + ' ' + self.part.name

class BuildPart(Build):
    pass

    class Meta:
        verbose_name = "Build Part"

为了使用order_by子句以正确的顺序获取所有内容,我们按照'family'字段访问PartFamily模型:

class PartFamily(models.Model):
    make = models.ForeignKey(PartMake)
    type = models.ForeignKey(PartType)
    name = models.CharField("Family Name", max_length=30,
                             unique=True)
    slug = models.SlugField(unique=True)

最后,我们使用'order'字段进入模型,我们希望按相关项排序,PartType:

class PartType(models.Model):
    name = models.CharField("Part Type", max_length=30, unique=True)
    slug = models.SlugField(unique=True)
    order = models.PositiveSmallIntegerField()
    description = models.TextField(blank=True, null=True)

1 个答案:

答案 0 :(得分:0)

在罗斯曼的帮助下,我能够找到自己问题的答案。 part_list 行应如下所示:

# views.py

part_list = product.buildpart.all().order_by('family__type')

一旦Roseman指出变量名称不匹配,我就使用QuerySet,因为它对我来说最有意义,而且它有效!