ForeignKey on Tastypie REST - The model '' has an empty attribute
Asked Answered
F

1

5

I need to list the working hours of each employee, but i'm getting:

The model '' has an empty attribute 'work_journey' and doesn't allow a null value.

on:

/rest/tastypie/employee/?format=json

models.py

class Employee():
    registration = models.CharField(u'Registration', max_length=20, unique=True)
    work_journey = models.ForeignKey(WorkJourney, null=True, blank=True)

hr.models.py

class WorkJourney(ModelPlus):
    code = models.CharField(max_length=10, null=True, unique=True)
    workinghours = models.CharField(max_length=40)
    excluded = models.BooleanField()

    class Meta:
        db_table='work_journey'
        verbose_name = u'Work Journey'

    def __unicode__(self):
        return self.workinghours

resources.py

from suap.models import Employee
from hr.models import WorkJourney


class WorkJourneyResource(ModelResource):
    class Meta:
        queryset = WorkJourney.objects.all()
        resource_name = 'work_journey'
        authentication = BasicAuthentication()

class EmployeeResource(ModelResource):
    journey = fields.ForeignKey(WorkJourney, 'work_journey')
    class Meta:
        queryset = Employee.objects.all()
        resource_name = 'employee'
        authentication = BasicAuthentication()
Forgiveness answered 7/2, 2013 at 13:14 Comment(0)
T
17

1/ You need a WorkJourneyResource rather than WorkJourney when you define your relation in ressoure.py

2/ To allow a null value, just add null=True, blank=True

Here is the code fixed:

class EmployeeResource(ModelResource):
    journey = fields.ForeignKey(WorkJourneyResource, 'work_journey', null=True, blank=True)
    ....
Theta answered 7/2, 2013 at 13:24 Comment(2)
My bad on WorkJourneyResource, it was ok on my code. It works adding null=True, blank=True. But it's just returning the resource_uri from work_journey..Forgiveness
This is a normal behaviour. add full=Trueon your fields.ForeignKey(..) accept my answer if it works ;-)Theta

© 2022 - 2024 — McMap. All rights reserved.