Search code examples
djangodjango-querysetdjango-1.7

Django prefetch_related using list object


Another prefetch_related question, yawn.

Using Django 1.7 an given models like this:

class Armor(models.Model):
    name = models.CharField(max_length=32)
    defense = models.IntegerField(max_length=18)

class Weapon(models.Model):
    name = models.CharField(max_length=32)
    attack = models.IntegerField(max_length=18)

class Alignment(models.Model):
    name = models.CharField(max_length=32)

# many more attribute models

class Knight(models.model):
    name = models.CharField(max_length=32)
    strength = models.IntegerField(max_length=18)
    iq = models.IntegerField(max_length=18)
    alignment = models.ManyToManyField(Alignment)
    weapons = models.ManyToManyField(Weapon, blank=True)
    armor = models.ManyToManyField(Armor, blank=True)
    #... many more m2ms

I need to see all the Knights on a page, but I really only care about their armor, weapons or alignment if a user selects on or more of those attributes as a filter.

E.g., if a user selects 'Alignment' and 'Weapons' on the page navigation, I want to show the weapon and alignment sets with each Knight.

In my view I have a list of all the attribute types the uses has chosen, I would like to pass that list to the queryset prefetch_related() method, i.e.,

selected_attributes = ['alignment','weapons']
Knight.objects.all().prefetch_related(selected_attributes)

But I can't seem to get it to work. Can I do it?


Solution

  • Use *args magic:

    Knight.objects.all().prefetch_related(*selected_attributes)