[英]Django ORM query: how to swap value of a attribute?
Here is the case. 就是这种情况。 I want to swap value of user.
我想交换用户的价值。
user_with_apple = User.objects.filter(fruit=apple)
user_with_pear = User.objects.filter(fruit=pear)
user_with_apple.update(fruit=pear)
user_with_pear.update(fruit=apple)
Well, this does not work, as everything ends up with pear. 嗯,这行不通,因为一切都以梨结尾。 Because django ORM is lazy, I suppose?
因为django ORM很懒,我想?
So may I ask how can I perform such a "swap" operation? 因此,请问如何执行这种“交换”操作? Do I have to use a intermediate value?
我必须使用中间值吗?
Thank you so much! 非常感谢!
Or does it make sense if I force the evaluation of the query by slicing or calling list() on it? 还是通过切片或调用list()来强制对查询求值,这有意义吗? eg.
例如。 user_with_apple = User.objects.filter(fruit=apple)[:] user_with_pear = User.objects.filter(fruit=pear)[:]
user_with_apple = User.objects.filter(fruit = apple)[:] user_with_pear = User.objects.filter(fruit = pear)[:]
I suppose you have CharField
for fruit
. 我想你有
CharField
做fruit
。 Then add unknown
option to choice. 然后将
unknown
选项添加到选择中。
FRUIT_CHOICES = (
...
(unknown, 'Unknown'),
(apple, 'Apple'),
(pear, 'Pear'),
...
)
class User(models.Model):
...
fruit = models.CharField(..., choices=FRUIT_CHOICES)
...
Then try this. 然后试试这个。
User.objects.filter(fruit=apple).update(fruit=unknown)
User.objects.filter(fruit=pear).update(fruit=apple)
User.objects.filter(fruit=unknown).update(fruit=pear)
Add access null values for fruit
field. 为
fruit
字段添加访问空值。
FRUIT_CHOICES = (
...
(apple, 'Apple'),
(pear, 'Pear'),
...
)
class User(models.Model):
...
fruit = models.CharField(..., blank=True, null=True, choices=FRUIT_CHOICES)
...
User.objects.filter(fruit=apple).update(fruit=None)
User.objects.filter(fruit=pear).update(fruit=apple)
User.objects.filter(fruit=None).update(fruit=pear)
Here is what that comes to mind: 这是我想到的:
If you call list
on your QuerySets, you force Django to give you the objects. 如果在QuerySet上调用
list
,则强制Django给您对象。 The problem with this is that you can't call update
on a list, so you need to iterate over the lists, and update each object. 这样做的问题是您无法在列表上调用
update
,因此需要遍历列表并更新每个对象。
This may help you on your way: 这可能会帮助您:
users_with_apple = list(User.objects.filter(fruit=apple))
users_with_pear = list(User.objects.filter(fruit=pear))
for user in users_with_apple:
user.fruit = pear
user.save()
for user in users_with_pear:
user.fruit = apple
user.save()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.