序列化程序创建的循环依赖

时间:2019-07-29 12:13:03

标签: python django django-rest-framework

将序列化器导入模型时,无法再导入模型,因此我怀疑存在循环依赖性。

当不导入序列化程序时,一切都会顺利进行,但是在导入时,一切都会中断。

这有效

from shift.models import Shift

class ShiftChangeRequest(models.Model):
    shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True)

这不是:

from shift.models import Shift
from shift.serializers.base import BaseSerializer

class ShiftChangeRequest(models.Model):
    shift = models.ForeignKey(Shift, on_delete=models.CASCADE, null=True)

您可以看到ShiftChangeRequest确实与shift有联系,但是在BaseSerializer中甚至没有提到ShiftChangeRequest:

from rest_framework import serializers
from shift import models


class BaseSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Shift
        fields = [
            "id",
            "title",
            "start",
            "end",
            "amount_of_minutes",
            "amount_of_employees",
            "client",
            "skills",
            "users",
            "repeat_at",
        ]

我希望一切都能像导入前一样工作,但出现错误ImportError: cannot import name 'ShiftChangeRequest'

ShiftChangeRequest被导入到ShiftChangeRequestSerializer中,如下所示:

from rest_framework import serializers
from shift_change.models import ShiftChangeRequest


class ShiftChangeRequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShiftChangeRequest
        fields = ["id", "user", "switch_user", "shift", "message", "type", "accepted"]
        extra_kwargs = {"user": {"allow_null": True, "required": False}}

    def create(self, validated_data):
        if "user" not in validated_data:
            validated_data["user"] = self.context["request"].user

        return super().create(validated_data)

2 个答案:

答案 0 :(得分:1)

您不需要导入Shift,可以按以下方式使用它。

from shift.serializers.base import BaseSerializer

class ShiftChangeRequest(models.Model):
    shift = models.ForeignKey('shift.Shift', on_delete=models.CASCADE, null=True)

元类中的内部序列化程序文件导入Shift

from rest_framework import serializers


class BaseSerializer(serializers.ModelSerializer):
    class Meta:
        from shift.models import Shift
        model = Shift
        fields = []

希望它将解决您的问题。

答案 1 :(得分:0)

models.py 中,删除以下行:

from shift.serializers.base import BaseSerializer

无需将Serializer类导入到models.py文件中