Sunday, January 21, 2018

How do I set the value of a model object's property after using `get_field()`?

I'm making a terminal command for my Django app:

    from django.core.management.base import BaseCommand, CommandError
   
from django.core.exceptions import FieldDoesNotExist
   
from django.apps import apps
   
   
   
class Command(BaseCommand):
       
def add_arguments(self, parser):
            parser
.add_argument(
               
"--app",
                dest
="app",
                required
=True,
           
)
   
            parser
.add_argument(
               
"--model",
                dest
="model",
                required
=True,
           
)
   
            parser
.add_argument(
               
"--col",
                dest
="col",
                required
=True,
           
)
   
       
def handle(self, *args, **options):
            app_label
= options.get('app')
            model_name
= options.get('model')
            column_name
= options.get('col')
   
           
try:
                model
= apps.get_model(app_label=app_label, model_name=model_name)
           
except LookupError as e:
                msg
= 'The model "%s" under the app "%s" does not exist!' \
                     
% (model_name, app_label)
               
raise CommandError(msg)
           
try:
                column
= model._meta.get_field(column_name)
           
except FieldDoesNotExist as e:
                msg
= 'The column "%s" does not match!' % column_name
               
raise CommandError(msg)
           
else:
               
print(column, type(column))
               
# Do stuff here with the column, model.


Right now, `column` is `<django.db.models.fields.IntegerField: column_name>`. I want this instance of `model` to have `column_name` set to `100`. How can I set and save this instance in this manner?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2caa4cd5-cb62-4bee-8e41-6182bfba792a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment