Search code examples
pythondjangotastypie

ForeignKey not displayed in Tastypie


Fields defined in my models as models.ForeignKey are not displayed in Tastypie. All fields are displayed except Client field. Quick and dirty fix is to add another field in Statement model like

ClientID = models.IntegerField(db_column='Client_id', max_length=32)

but this seems wrong to me. Does anyone know better solution?

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

Solution

  • In Tastypie you have to define all relational fields in ModelResources definition. So if you got some let say foreign key in model you have to define that foreign key again in model resource. The reason for that is Tastypie has to know how to deal if it. Has to know serialization, authorization, authentication, etc for it. Other ways the field be ignored. You have to pass that related resource and that's it.

    class StatementResource(ModelResource):
        Client = fields.ForeignKey(ClientResource, 'Client')
        class Meta:
            queryset = Statement.objects.all()
            resource_name = 'client'
            allowed_methods = ['get']
            include_resource_uri = False