[英]Django / Sqlite3 add a row for model with a foreign key
I'm new to both Django and SQlite3. 我是Django和SQlite3的新手。 I have a model (Person), with a foreign key to (Person_Type):
我有一个模型(Person),它带有(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. 我正在尝试使用python manage.py shell将条目添加到Person。
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. 但这会返回错误:ValueError:无法分配“ Appellant”:“ Person.pers_type”必须是“ Person_Type”实例。
The string "Appellant" is already being stored as one of the values in the "Person_Type.pers_type" table. 字符串“ Appellant”已经作为值之一存储在“ Person_Type.pers_type”表中。 What do I need to change to get this to reference the pers_type field?
我需要更改什么才能使其引用pers_type字段?
Happy to provide more details if needed. 如果需要,很高兴提供更多详细信息。 Thanks very much for your time.
非常感谢你花时间陪伴。
Person.objects.create(name='Adam', person_type='Appellant')
Here, as person_type argument, create() method expects to get person_type instance not string 在这里,作为person_type参数,create()方法期望获取person_type实例而不是字符串
So just prowide: 所以只是广泛:
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: 或考虑到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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.