This is my first time using Django querysets in such detail so I am a little confused.
I have two models:
Asset (Django model but not managed by Django):
id = models.BigIntegerField(primary_key=True, db_index=True, editable=False)
asset = models.CharField(
max_length=255, null=False
)
ip = models.CharField(
max_length=255,
null=True,
)
entity = models.ForeignKey(
Entity,
on_delete=models.CASCADE,
related_name="owned_assets",
db_constraint=False,
)
Software (same as above – not managed by Django):
id = models.BigIntegerField(primary_key=True, db_index=True, editable=False, null=False)
entity = models.ForeignKey(
Entity,
db_constraint=False,
null=False,
)
asset = models.ForeignKey(
Asset, db_constraint=False, null=False
)
software = models.CharField(
max_length=64, null=False
)
version = models.CharField(
max_length=64, null=False
)
When a user GETs all assets, I want to decorate the Asset queryset with the related Software. A software entry is not unique across asset and entity though, a single asset can have multiple software entries associated with it. What would be the best way to go about annotating the base Asset queryset with these software entries? How do I add a list of software and version to a single Asset in the queryset?
Is it possible to do this in the DB and not in memory? Thank you
assetsqueryset, you can lookupasset.software_set.all()to obtain all relatedSoftwareobjects. You can use.prefetch_related(..)to do the JOINing in "bulk" in memory, to avoid making an extra query to the database perAsset.