I am trying to put values to my django database.
My app_name/models.py looks like:
from django.db import models
# Create your models here.
class Language(models.Model):
id = models.AutoField(primary_key=True)
code = models.TextField(max_length=14)
I ran this commands:
python3 manage.py makemigrations app_name
python3 manage.py migrate app_name
After that I starting importing values to my database. So I run this command:
python3 manage.py shell
and put this code to the shell:
from app_name.models import *
with open('lang.txt', 'r') as file:
for i in file:
a = Language.objects.create(code=i.strip())
File lang.txt contains 309 lines with language codes. The file looks like:
en
fr
af
de
...
When I run this code in the manage.py shell Django created 309 Language objects. But when I try type random id in the shell -> Language(id=1).code
it return only empty string - ''
.
I tried use save() method too but still same problem.
from definitions.models import *
with open('lang.txt', 'r') as file:
for i in file:
a = Language(code=i.strip())
a.save()
Django version 1.10.1
So my question is where can be a problem?
This is happening because you are not fetching Language
objects properly.
When you do Language(id=1).code
, You are instantiating Language object with no value in given to code field.
In django, to fetch a object, you do Model.objects.get(field=value)
. So your code becomes:
Language.objects.get(id=1).code