How do I get all the items associated with a part via the self-referential ManyToManyField? How to I fix my view to get part_list to contain a list of all the parts associated with 'product' and in the order specified by 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())
Here's the template:
# 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 %}
Notice the PartModel model holding our inventory and its self-referential BuildPart ManyToMany model through the buildpart field:
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"
To get everything in the right order with the order_by clause we follow the 'family' field to the PartFamily model:
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)
And lastly, we get to the model with the 'order' field, the one we wish to sort the related items by, 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)
I was able to find an answer to my own question with Roseman's help. The part_list line should be as follows:
# views.py
part_list = product.buildpart.all().order_by('family__type')
Once Roseman pointed out the variable name mismatch I did up the QuerySet as it made the most sense to me, and it works!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.