django - How can I manually edit a specific attribute in a model through Django Shell?
问题描述
I recently added a created_by
attribute in Store
model. Since this automatically gets a current logged in user when a store is created, if I don't manually assign any user, that column will be forever null.
class Store(models.Model):
...
created_by = ForeignKey(settings.AUTH_USER_MODEL, related_name='stores_of_created_by', null=True, blank=True)
So, I want to assign a user manually. I think Django Shell (something that can be triggered through python manage.py shell) would be a good way to assign users manually.
I'm very confused how I can manually assign a user in a specific attribute of all stores. So far I got a specific user and all stores in the following way.
from django.contrib.auth.models import User
from boutique.models import Store
stores = Store.objects.all()
user = User.objects.get(username='admin@gmail.com')
After that, I need to loop through all stores and assign the user in created_by
of all stores. How can I do that in Django Shell
?
解决方案
Try this
from django.contrib.auth.models import User
from boutique.models import Store
stores = Store.objects.all()
user = User.objects.get(username='admin@gmail.com')
for store in stores:
store.created_by = user
store.save()
loop through the Store
QuerySet and assign created_by
attribute with specific User
instance (here it is user
)
If you wish to create Store
objects with created_by
as admin, change your model as below,
from django.contrib.auth.models import User
def default_admin():
return User.objects.get(username='admin@gmail.com')
class Store(models.Model):
created_by = ForeignKey(settings.AUTH_USER_MODEL, related_name='stores_of_created_by', default=default_admin)
推荐阅读
- python - 将 pack_padded_sequence 与 Transformer 一起使用会出错
- image-processing - 扁平化图像旋转矩阵
- sql - 如何使用 with CTE (WITH CTE- common_table_expression) 更新雪花中的语句?
- sql - SQL Server 聚合窗口的区别
- jquery - 标签功能的jQuery切换或滑动?
- angular - 组件 url 显示是应用中任意 url 地址的首页
- delphi - 如何在 Delphi 11 Alexandria 中选择 Android 平台?
- macos - 在 Mac OS 上安装 Hadoop 的问题
- python - 从一个excel表的列中的单元格中获取值,并检查该值是否存在于其他excel表的列中
- r - 如何从数据集中迭代地提取 compare_means 值