0

I want to generate multiple country objects with the similar language object without going through the admin UI.

models.py

from django.db import models

class World(models.Model):
    country = models.CharField(max_length=200)
    Language = models.CharField(max_length=200)

class add_countries(models.Model):
    sub_part1 = ['USA','ENGLAND','AUSTRALIA','CANADA']
    for sub in sub_part1:
        sub = World.country
        World.Language = "English"

add_countries()
2
  • What exactly is going wrong? I'm guessing you're getting some syntax errors to start with. You could have a look at get_or_create Commented Jun 15, 2018 at 8:57
  • I am not able to see any errors. Nor am I able to see ['USA','ENGLAND','AUSTRALIA','CANADA'] added Commented Jun 15, 2018 at 9:00

2 Answers 2

1
    for country in ['USA','ENGLAND','AUSTRALIA','CANADA']:
        World.objects.get_or_create(country=country, language='English')

You can put above code inside a method and call that.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much.
1

If you're looking to have a few database entries that are always there, you should probably consider using data migrations. This would result in these database rows being created when you migrate your database. The basic idea would be something like this:

from django.db import migrations

def add_languages(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    World = apps.get_model('yourappname', 'World')
    languages = {'English': ['USA','ENGLAND','AUSTRALIA','CANADA']}
    for language, countries in languages.items():
        for country in countries:
            World.objects.get_or_create(country=country, Language=language)

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_languages),
    ]

The migration file would be in your app's migrations directory (something like project_root/yourappname/migrations/0002_insert_languages.py in this case). Consult the documentation for more information.

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.