Django / Sqlite3 add row for model with foreign key

I am new to Django and SQlite3. I have a model (Person) with a foreign key (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 an instance of "Person_Type".

The string "Appellant" is already stored as one of the values ​​in the table "Person_Type.pers_type". What do I need to change to make this refer to the pers_type field?

We are pleased to provide more detailed information if necessary. Thanks so much for your time.

+4
source share
1 answer
 Person.objects.create(name='Adam', person_type='Appellant') 

Here, as the argument to person_type, the create () method expects to get an instance of person_type, not a string

So simple nationwide:

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

or, given the case where "Appellant" is 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) 
+4
source

All Articles