1

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?

3
  • 1
    Do you get an empty string using Language.objects.get(id=1), too? Commented Jul 31, 2017 at 19:24
  • No, I see text what I excpected. Why get() method shows right string and Language(id=1).code shows empty string? Thanks Commented Jul 31, 2017 at 19:29
  • 1
    That's the way Django interacts with the db. Using the objects.get method. I think its time for reading ;) Commented Jul 31, 2017 at 19:32

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.