Вопрос

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