我需要列出每个员工的工作时间,但我得到:

模型”的属性'work_journey'为空,不允许为空值。

上:

/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()

最佳答案

1/在ressoure.py中定义关系时,您需要WorkJourneyResource而不是WorkJourney
2/要允许为空值,只需添加null=True, blank=True
这是固定的代码:

class EmployeeResource(ModelResource):
    journey = fields.ForeignKey(WorkJourneyResource, 'work_journey', null=True, blank=True)
    ....

关于django - Tastypie REST上的ForeignKey-模型 ''具有空属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14752007/

10-12 22:18