I need to retrieve a value from a Many-To-Many query. Let's say I have 3 models: Toy, Part, and ToyParts
ToyParts has a field called "part_no". I need to be able to get the value of this.
class Toy(models.Model):
parts = models.ManyToManyField(Part, through="ToyParts")
class Part(models.Model):
pass
class ToyParts(models.Model):
toy = models.ForeignKey(Toy, ...)
part = models.ForeignKey(Part, ...)
part_no = models.CharField(...)
I've tried using:
toy.parts.all().first().part_no
which obviously doesn't work as Part does not have a field called "part_no"
I've also tried just simply using:
ToyParts.objects.filter(toy=..., part=...)
but that adds additional queries.
How would I be able to get part_no without querying ToyParts directly?
The
part_nofield is declared on the modelToyParts. You therefore need to get an instance ofToyPartsto access this field. Assuming you have aToyinstance you can use the reverse relation toToyParts, which defaults totoyparts_set, as follows:You can't. If you want to reduce the number of queries you can use
select_related:In this example
tp.partdoesn't require an extra query as the part instance is already fetched byselect_related.