是否有“正確”的方法來轉換django.db.models.query ?ValuesListQuerySet到純列表?

[英]Is there a “proper” way to convert django.db.models.query.ValuesListQuerySet to a pure List?


I'm attempted to delete records from a number of models in a single method, were I have the following schema:

如果我有以下模式,我嘗試用一個方法從多個模型中刪除記錄:

picture 1:1 picture_foreign_picture *:1 picture_foreign

I'm deleting these given list picture_foreign objects:

我正在刪除這些給定列表picture_foreign對象:

picture_foreign_pictures = PictureForeignPicture.objects.filter(picture_foreign__in=picture_foreigns)
picture_ids = picture_foreign_pictures.values_list('picture_id', flat=True)
logger.warn('PICTURES REMOVE: %s' % picture_ids)
picture_foreign_pictures.delete()
logger.warn('PICTURES REMOVE: %s' % picture_ids)

The 2 loggers lines output the following:

兩個日志記錄程序行輸出如下:

WARNING 2013-01-02 03:40:10,974 PICTURES REMOVE: [86L]
WARNING 2013-01-02 03:40:11,045 PICTURES REMOVE: []

Despite this however, the picture 86 still exists:

盡管如此,這幅圖86仍然存在:

mysql> select id from picture where id = 86;
+----+
| id |
+----+
| 86 |
+----+
1 row in set (0.00 sec)

I guess I could get around this by simply converting picture_ids into a pure integer list however I'm wondering whether there's a more Django method to this? I would have thought flat=True would already handle this but it seems to be more than just a pure list.

我想我可以通過簡單地將picture_id轉換成一個純整數列表來解決這個問題,但是我想知道是否有更多的Django方法可以實現這個目的?我原以為是flat=True會處理這個,但它似乎不僅僅是一個純粹的列表。

2 个解决方案

#1


26  

Well, I'm not sure it's proper, but it's ridiculously simple to use list() to accomplish this:

嗯,我不確定它是否合適,但是使用list()實現這一點非常簡單:

picture_ids = list(picture_foreign_pictures.values_list('picture_id', flat=True))

#2


4  

Above solution is not working:

以上解決方案無效:

You can convert to pur list like this:

你可以這樣轉換到pur列表:

p_ids =PictureForeignPicture.objects.filter(picture_foreign__in=picture_foreigns).values_list('picture_id', flat=True)

new_list = [];new_list.extend(p_ids)

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/01/02/72ef837020a098fdf6d51e0ae6188642.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com