我的模型中定义为models.ForeignKey的字段未显示在Tastypie中。除客户端字段外,显示所有字段。 快速而肮脏的修复是在Statement模型中添加另一个字段,如
ClientID = models.IntegerField(db_column='Client_id', max_length=32)
但这对我来说似乎不对。有谁知道更好的解决方案?
models.py
class Client(models.Model):
ID = models.AutoField(primary_key=True)
F1 = models.CharField(max_length=256, null=True)
F2 = models.CharField(max_length=256, null=True)
class Statement(models.Model):
ID = models.AutoField(primary_key=True)
Client = models.ForeignKey(Client, related_name='statements')
State = models.CharField(max_length=256, null=True)
Address = models.CharField(max_length=256, null=True)
api.py
class StatementResource(ModelResource):
class Meta:
queryset = Statement.objects.all()
resource_name = 'client'
allowed_methods = ['get']
include_resource_uri = False
class ClientResource(ModelResource):
statements = fields.ToManyField(StatementResource, 'statements', null=True, blank=True, full=True)
class Meta:
queryset = Client.objects.all()
resource_name = 'client'
allowed_methods = ['get']
include_resource_uri = False
答案 0 :(得分:0)
在Tastypie中,您必须在ModelResources定义中定义所有关系字段。因此,如果您在模型中有一些说外键,则必须在模型资源中再次定义该外键。原因是Tastypie必须知道如何处理它。必须知道它的序列化,授权,认证等。该领域被忽视的其他方式。你必须传递那个相关的资源,就是这样。
class StatementResource(ModelResource):
Client = fields.ForeignKey(ClientResource, 'Client')
class Meta:
queryset = Statement.objects.all()
resource_name = 'client'
allowed_methods = ['get']
include_resource_uri = False