您好我在我的Tastypie
项目中使用Django
。当我获取与资源api
中的其他模型具有外键关系的模型值时,其返回空值。
我使用MySql作为我的数据库。
我的型号代码:
TopicDetail
模型
class Topicdetails(models.Model):
apptopicid = models.IntegerField(db_column='appTopicID', primary_key=True) # Field name made lowercase.
portaltopicid = models.IntegerField(db_column='portalTopicID', blank=True, null=True) # Field name made lowercase.
topicname = models.CharField(db_column='topicName', max_length=500, blank=True) # Field name made lowercase.
topicshortdescription = models.CharField(db_column='topicShortDescription', max_length=5000, blank=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'TopicDetails'
Instructor Detail
模型
class Instructordetails(models.Model):
appinstructorid = models.IntegerField(db_column='appInstructorID', primary_key=True) # Field name made lowercase.
portalinstructorid = models.IntegerField(db_column='portalInstructorID') # Field name made lowercase.
firstname = models.CharField(db_column='firstName', max_length=50, blank=True) # Field name made lowercase.
middlename = models.CharField(db_column='middleName', max_length=50, blank=True) # Field name made lowercase.
lastname = models.CharField(db_column='lastName', max_length=50, blank=True) # Field name made lowercase.
optionalid = models.IntegerField(db_column='optionalID', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'InstructorDetails'
TopicInstructor
模型,其中两个模型有两个外键。
class Topicinstructor(models.Model):
topicinstructorrelationid = models.IntegerField(db_column='topicInstructorRelationID', primary_key=True) # Field name made lowercase.
apptopicid = models.ForeignKey(Topicdetails, db_column='appTopicID') # Field name made lowercase.
appinstructorid = models.ForeignKey(Instructordetails, db_column='appInstructorID') # Field name made lowercase.
class Meta:
managed = False
db_table = 'TopicInstructor'
我的TopicInstructor api代码:
class TopicinstructorResource(ModelResource):
# topicdetails = fields.ForeignKey(TopicdetailsResource,'topicdetails')
#instructordetails = fields.ForeignKey(InstructordetailsResource, 'instructordetails')
class Meta:
queryset = Topicinstructor.objects.all()
resource_name = 'topicinstructor'
include_resource_uri = False
如果我在我的资源api上面两行代码注释,则显示错误:
{
error: "The model '<Topicinstructor: Topicinstructor object>' has an empty attribute 'instructordetails' and doesn't allow a null value."
}
如果获取资源,它返回输出如下:
{
meta: {
limit: 20,
next: "/api/topicinstructor/?offset=20&limit=20&format=json",
offset: 0,
previous: null,
total_count: 994
},
objects: [
{
topicinstructorrelationid: 1
},
{
topicinstructorrelationid: 2
},
{
topicinstructorrelationid: 3
},
{
topicinstructorrelationid: 4
},
]
}
但我还需要获取外键值。更多内容我使用python manage.py inspectdb
命令从MySql数据库创建了我的模型文件。
请帮助我......
答案 0 :(得分:0)
将null=True
放置为允许空值
topicdetails = fields.ForeignKey(TopicdetailsResource,'topicdetails',null=True)
instructordetails = fields.ForeignKey(InstructordetailsResource,'instructordetails',null=True)