How to saving dict into models in Views Django


If you deploy views and need to saving data into models, you should considering dictionaries type rather with standard. For instance, this is standard way to save data into django models :

1
2
3
4
5
# This is standar way
def index(request):
    mymodel = Bug(qid = ‘1’, subject = ‘subject’,
                  content = ‘content’, date = ‘20110801’)
    mymodel.save()


What if we have a lot of keys here ?
Then you should consider using dictionaries.
For instance :

1
2
3
4
5
6
# This use dictionaries
def index(request):
    data = {‘qid’: ‘1’, ‘subject’: ‘subject’,
            ‘content’: ‘content’, ‘date’: ‘20110801’}
    mymodel = Bug(**data)
    mymodel.save()

I have fault before when using dictionaries.

1
int() argument must be a string or a number, not ‘dict’

Because I’m forgot using “**” before dictionaries. Remember, django models format is class Models(**kwargs) 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.