0

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?

4

2 回答 2

1

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)
于 2018-09-25T07:16:45.033 回答
1

If you are updating all the stores, this will be faster. Iterating over the stores fetches the record from the db and writes the updated record, causing atleast twice as many queries as the number of records in the DB.

admin = User.objects.get(username='admin@gmail.com') Store.objects.update(created_by=admin)

This shall update all the stores in just two queries.

于 2018-09-26T10:39:49.443 回答