我是Django的新手,并试图了解如何在模型中设置数据库关系。我有以下两种型号:
class BusinessTypes(models.Model):
categoryID = models.AutoField(db_column='TypeID', primary_key=True) # Field name made lowercase.
category = models.CharField(db_column='type', max_length=200)
newtype = models.CharField(db_column='newType', max_length=200) # Field name made lowercase.
dec = models.CharField(max_length=255)
tabsize = models.CharField(db_column='tabSize', max_length=10) # Field name made lowercase.
#subcategory = models.ForeignKey(BusinessTypesSub, to_field='Type_ID')
class Meta:
managed = False
db_table = 'business_types'
app_label = 'sapi'
class BusinessTypesSub(models.Model):
subcategoryID = models.AutoField(db_column='Type_subID', primary_key=True) # Field name made lowercase.
categoryID = models.IntegerField(db_column='Type_ID') # Field name made lowercase.
status = models.IntegerField()
showpub = models.IntegerField(db_column='showPub') # Field name made lowercase.
showcity = models.CharField(db_column='showCity', max_length=20) # Field name made lowercase.
subcategory = models.CharField(db_column='sub', max_length=255)
sub_alternative = models.CharField(max_length=255)
category = models.ForeignKey(BusinessTypes,from_field='Type_ID', to_field='TypeID')
class Meta:
managed = False
db_table = 'business_types_sub'
app_label = 'api'
business_types和business_types_sub表之间存在一对多关系。我想设置一个外键关系,这样如果我创建一个通过BusinessTypesSub调用序列化程序的视图,我可以访问BusinessTypesModel中类别字段的值。外键关系应该是从BusinessTypesSub字段'Type_ID'到BusinessTypes字段'TypeID'。
我该如何创建?我尝试将以下内容添加到BusinessTypesSub模型中,但它只是创建了以下错误:
category = models.ForeignKey(BusinessTypes,to_field='TypeID')
BusinessTypes has no field named 'TypeID'
另外,我如何在视图/序列化器中调用它。例如,如何将“类别”添加到以下序列化程序:
class BusinessTypesSubSerializer(serializers.ModelSerializer):
category = serializers.RelatedField(source='BusinessType', read_only=True)
class Meta:
model = BusinessTypesSub
fields = ('categoryID', 'category', 'subcategoryID', 'subcategory')
答案 0 :(得分:0)
您指定了错误的to_field,它应该是BusinessType类的categoryID字段的名称,而不是数据库中列的名称:
category = models.ForeignKey(BusinessTypes, to_field='categoryID')
要在BusinessTypesSubSerializer中显示类别,您可以从此处定义的几个选项中进行选择:http://www.django-rest-framework.org/api-guide/relations/。例如。对于StringRelatedField,您可以定义:
class BusinessTypesSubSerializer(serializers.ModelSerializer):
category = serializers.StringRelatedField(read_only=True)
class Meta:
model = BusinessTypesSub
fields = ('categoryID', 'category', 'subcategoryID', 'subcategory')