【问题标题】:ForeignKey not displayed in Tastypie外键未显示在 Tastypie 中
【发布时间】:2014-08-08 14:38:34
【问题描述】:

在我的模型中定义为 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

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    在 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
    

    【讨论】:

    • 如果我在 StatementResource 中包含这一行:“Client = fields.ForeignKey(ClientResource, 'Client')”,则会出现错误“名称 'ClientResource' 未定义”。我是否应该在 StatementResource 之前定义 ClientResource,而不是关于 StatementResource 未定义的错误。
    • 在 ClientResource 周围使用单引号,例如 "Client = fields.ForeignKey('ClientResource', 'Client')" 解决了这个问题。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多