如何从django中的'ValuesListQuerySet'中删除一个值?

[英]How to delete a value from 'ValuesListQuerySet' in django?


In django, I am using a value list returned by a query in choice field. If any value is already submitted by user then I do not want to show that value in choice field. Hence I want to delete value from ValuesListQuerySet.

在django中,我使用选择字段中的查询返回的值列表。如果用户已经提交了任何值,那么我不想在选择字段中显示该值。因此,我想从ValuesListQuerySet中删除值。

Or is there another solution to accomplish this?

或者是否有其他解决方案来实现这一目标

1 个解决方案

#1


1  

Lets say you have a model Device which is assigned to a model User. A new device should only get a user which does not have any device yet. So we want to exclude the users in your choice field which already have a device:

假设您有一个模型设备,它被分配给模型用户。新设备应该只能获得没有任何设备的用户。因此,我们要排除您选择字段中已有设备的用户:

User.objects.exclude(pk__in=Device.objects.values_list('user', flat=True).distinct())

The inner query gets only the distinct values of the Device's user field. And we use that list of primary keys to exclude all those users in the outer query.

内部查询仅获取Device的用户字段的不同值。我们使用该主键列表来排除外部查询中的所有用户。

Be aware that this query has to be reevaluated each time you create such a form. If you only do it once in the form field definition, it will not be updated after new records are created. Look here how to do that: https://stackoverflow.com/a/3420588/640916

请注意,每次创建此类表单时都必须重新评估此查询。如果您只在表单字段定义中执行一次,则在创建新记录后不会更新它。在这里看看如何做到这一点:https://stackoverflow.com/a/3420588/640916

关注微信公众号

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/03/12/7d97848c720f6bd4a9f427511ab19bc7.html



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