Ich habe mich oft mit diesem Thema auseinandergesetzt, aber ich habe nicht versucht, tiefer darüber zu graben. Jetzt verstehe ich das Hauptproblem.
Dieses Mal bestand mein Problem darin, Serializer (Django und Restframework) aus verschiedenen Modulen wie den folgenden zu importieren:
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
# the line below was the problem 'srlzprod'
from products import serializers as srlzprod
Ich hatte ein Problem wie dieses:
from product import serializers as srlzprod
ModuleNotFoundError: No module named 'product'
Was ich erreichen wollte, war Folgendes:
class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
# the nested relation of the line below
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
Wie in den obigen Zeilen erwähnt, wie es zu lösen ist (Import auf oberster Ebene), nehme ich die folgenden Änderungen vor:
# change
product = srlzprod.ProductsSerializers(fields=['id','name',],read_only=True,)
# by
product = serializers.SerializerMethodField()
# and create the following method and call from there the required serializer class
def get_product(self, obj):
from products import serializers as srlzprod
p_fields = ['id', 'name', ]
return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,
).data
Daher wurde django runserver ohne Probleme ausgeführt:
./project/settings/manage.py runserver 0:8002 --settings=settings_development_mlazo
Performing system checks...
System check identified no issues (0 silenced).
April 25, 2020 - 13:31:56
Django version 2.0.7, using settings 'settings_development_mlazo'
Starting development server at http://0:8002/
Quit the server with CONTROL-C.
Der Endzustand der Codezeilen war folgender:
from rest_framework import serializers
from common import serializers as srlz
from prices import models as mdlpri
class CampaignsProductsSerializers(srlz.DynamicFieldsModelSerializer):
bank_name = serializers.CharField(trim_whitespace=True,)
coupon_type = serializers.SerializerMethodField()
promotion_description = serializers.SerializerMethodField()
product = serializers.SerializerMethodField()
class Meta:
model = mdlpri.CampaignsProducts
fields = '__all__'
def get_product(self, obj):
from products import serializers as srlzprod
p_fields = ['id', 'name', ]
return srlzprod.ProductsSerializers(
obj.product, fields=p_fields, many=False,
).data
Hoffe das könnte für alle anderen hilfreich sein.
Schöne Grüße,