如何从Pony ORM中的Set()中仅获取一个图像

时间:2015-05-30 16:47:15

标签: python ponyorm

实体:

class Car(db.Entity):
    image = Set("Image")
    name = Required(str, 40,)

class Image(db.Entity):
    name = Required(str, unique=True)
    car = Required(Car)

我希望获得有关汽车列表页面的信息:一辆车 - 该车的一张图片。

我用:

cars = select((car, car.image) for car in Car).distinct().show()

我有

Car[1]|Image[1]  
Car[1]|Image[2]  
...
Car[5]Image[1]
Car[5]Image[2]
...

但我只需要每辆车的第一张图片,而不是所有图片。

怎么做?

谢谢!

1 个答案:

答案 0 :(得分:3)

代码只获取每辆车的第一张图片(ID最低的图片):

#!/usr/bin/env python
from pony.orm import *

db = Database()
db.bind('sqlite', ':memory:', create_db=True)


class Car(db.Entity):
    image = Set("Image", lazy=True)
    name = Required(str, 40)

class Image(db.Entity):
    name = Required(str, unique=True)
    car = Required(Car)    

db.generate_mapping(create_tables=True)

sql_debug(True)

with db_session:
    car1 = Car(name='car1')
    car2 = Car(name='car2')
    image1 = Image(name='image1', car = car1)
    image2 = Image(name='image2', car = car1)
    image3 = Image(name='image3', car = car2)
    cars = select((car, car.name, image, image.name) for car in Car for image in car.image if image.id == min(car.image.id)).show()

结果:

GET CONNECTION FROM THE LOCAL POOL
SWITCH TO AUTOCOMMIT MODE
BEGIN IMMEDIATE TRANSACTION
INSERT INTO "Car" ("name") VALUES (?)
[u'car1']

INSERT INTO "Car" ("name") VALUES (?)
[u'car2']

INSERT INTO "Image" ("name", "car") VALUES (?, ?)
[u'image1', 1]

INSERT INTO "Image" ("name", "car") VALUES (?, ?)
[u'image2', 1]

INSERT INTO "Image" ("name", "car") VALUES (?, ?)
[u'image3', 2]

SELECT "car"."id", "car"."name", "image"."id", "image"."name"
FROM "Car" "car"
  LEFT JOIN "Image" "image-1"
    ON "car"."id" = "image-1"."car"
  LEFT JOIN "Image" "image"
    ON "car"."id" = "image"."car"
GROUP BY "car"."id", "car"."name", "image"."id", "image"."name"
HAVING "image"."id" = MIN("image-1"."id")

car   |car.name|image   |image.name
------+--------+--------+----------
Car[1]|car1    |Image[1]|image1    
Car[2]|car2    |Image[3]|image3    
COMMIT
RELEASE CONNECTION

顺便说一句,生成的sql很奇怪,我不认为执行两个相同的左连接是有道理的。 编辑:好的,这很有意义(见评论)。