Django / Sqlite3 add a row for model with a foreign key

Question:

I’m new to both Django and SQlite3. I have a model (Person), with a foreign key to (Person_Type):

class Person(models.Model):
    name = models.CharField(max_length=500)
    pers_type = models.ForeignKey(Person_Type)

    def __unicode__(self):
        return self.name

class Person_Type(models.Model):
    pers_type = models.CharField(max_length=40)

    def __unicode__(self):
        return self.pers_type

I am trying to add entries to Person using the python manage.py shell.

So far, I have tried:

import sqlite3
from trials.models import *

conn = sqlite3.connect('privy.db')
print Person #this returns <class 'privy.trials.models.Person'>
cur = conn.cursor()
fields = ['name', 'pers_type']
row = ['Adam', 'Appellant']
Person.objects.create(**dict(zip(fields, row)))

But this returns an error: ValueError: Cannot assign “‘Appellant'”: “Person.pers_type” must be a “Person_Type” instance.

The string “Appellant” is already being stored as one of the values in the “Person_Type.pers_type” table. What do I need to change to get this to reference the pers_type field?

Happy to provide more details if needed. Thanks very much for your time.

Asked By: Adam

||

Answers:

Person.objects.create(name='Adam', person_type='Appellant') 

Here, as person_type argument, create() method expects to get person_type instance not string

So just provide:

pers_type = Person_Type.objects.get(pers_type='Appelant') # assuming pers_type is unique
Person.objects.create(name='Adam', pers_type=pers_type) 

or, taking into account case when ‘Appellant’ not present in db:

try:
    pers_type = Person_Type.objects.get(pers_type='Appelant')
except Person_Type.DoesNotExists:
    person_type = Person_Type.objects.create(pers_type='Appellant')
Person.objects.create(name='Adam', pers_type=pers_type)
Answered By: Pill