Let's say I have a database with movies, books, and software, and they all inherit the same element model.
class Item(models.Model):
...
class Movie(models.Model):
item = models.OneToOneField(Item)
...
class Book(models.Model):
item = models.OneToOneField(Item)
...
class Software(models.Model):
item = models.OneToOneField(Item)
...
Now I want to query the database on the Item, but I want to pick a related object for this item, whether it be Movie, Book or Software. If all the objects were of the same type, say, films, then I could do the following:
Item.objects.prefetch_related('movie')
However, I need to be able to get the associated object no matter what type it is. Can i run:
Item.objects.prefetch_related('movie', 'book', 'software')
Will it find a related object no matter what type it is, and will it be effective? Is there a better way to do this?
source
share