سؤال

I have some mptt model:

class Locations(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    type = models.ForeignKey('LocationTypes')
    title = models.CharField(max_length=100)

Some models related with it:

class Building(models.Model):
    title = models.CharField(max_length=100)
    location = models.ForeignKey('Locations')

And QuerySet like this:

building_list = Building.objects.filter(title__icontains='house')

I know some "Location" "id", but not directly related to Building, one of ancestors. What better way to left in building_list, only those elements the is location one of descendants(not necessarily direct) of this "Location"?

هل كانت مفيدة؟

المحلول

You can get descendants list if you know location id with function get_descendants:

location = Location.objects.get(pk="some_location_id")
descendants = location.get_descendants().values_list('id', flat=True)
building_list = Building.objects.filter(title__icontains='house',
                                        location__in=descendants)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top