how to filter data in different models in django?

my models

class Player(TimeStampedModel):
    name = models.CharField(max_length=200)
    email = models.CharField(max_length=200)
    email_verified = models.BooleanField(default=False, blank=True)
    phone = models.CharField(max_length=200)
    phone_verified = models.BooleanField(default=False, blank=True)
    company_id = models.ImageField(upload_to=get_file_path_id_card, null=True, 
    max_length=255)
    company_id_verified = models.BooleanField(default=False, blank=True)
    team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.name 

this is my model , how to filter data in multiple model?


Solution 1:

You can use a Queryset to filter by modal object's field.

You can use this to also filter relationships on models.

In your example, you can do a filter of all the Player entries that have a Character that have Weapon with strength > 10 Player.objects.filter(character__weapon__strength__gt=10)

You can also separate them out into 3 variables for readability purposes.

player_q = Player.objects.filter(character__isnull=False)
ch_q = player_q.filter(weapon__isnull=False)
wpn_dmg = ch_q.filter(strength__gt=10)

Please note that filters are lazy and thus don't return actual model instances untill they're evaluated. I think in this case gt returns an instance.

This documentation goes over all the fieldset lookups you can do with QuerySet object methods filter(), get(), and exclude()