首页 > 解决方案 > 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?

标签: djangodjango-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)

推荐阅读