views:

76

answers:

2

Hi there,

I have a model "Item", which has a 1:n to "Location". Means, there is a location-history for items.

Location has a FK to "Room", "Room" to "Floor" and "Floor" to "Building". Now, I want to select all Items which are currently located an a specific Floor.

I could solve it with a list comprehension, but is there any nicer way to solve it with one query?

-- Update --

Thanks for your answers, unfortunately, they do not match the requirement. To clarify the issue, here some code snippets of the models:

class Item(models.Model):
    [..]

class Location(models.Model):
    item = models.ForeignKey(Item)
    room = models.ForeignKey(Room)
    created_at = models.DateTimeField(auto_now_add=True)
    [..]


class Room(models.Model):
        floor = models.ForeignKey(Floor)
        [..]

class Floor(models.Model):
        building = models.ForeignKey(Building)
        [..]

class Building(models.Model):
        [..]

I want to get all items that are currently located on a specific floor, specified by a floor id (as you can see in the models, an item can be relocated). Thanks again.

A: 

I don't know your models exactly, but something like that should do it:

items_on_floor_one = Item.objects.filter(\
                     location__in=Location.objects.filter(room__floor__number=1,\
                     room__floor__building__name='my_building'))
lazerscience
thanks, see my update above.
schneck
A: 
items = Item.objects.filter(location__room__floor__name='building 1', location__room__floor__num=1)
dannyroa
also thanks, I updated the question above.
schneck