Django Serializer не является сериализуемым JSON
Я пытаюсь сериализовать детали объекта, который содержит ForeignKey
и OneToOneField
.
Вот моя модель:
user = models.OneToOneField(
"User",
on_delete=models.CASCADE,
null=False,
blank=False,
verbose_name="User",
help_text="The user who subscribed.",
related_name="subscription_information",
unique=True,
)
subscription = models.ForeignKey(
Subscription,
on_delete=models.CASCADE,
null=False,
blank=False,
related_name="subscription_information",
verbose_name="Subscription",
help_text="This is the subscription.",
)
subscription_type = models.IntegerField(
choices=SUBSCRIPTION_TYPES_CHOICES,
default=SubscriptionTypes.monthly,
null=False,
blank=False,
verbose_name="Subscription Type",
help_text="",
)
next_payment_amount = models.FloatField(
default=0.0,
null=False,
blank=True,
verbose_name="Subscription Plan Next Payment Amount",
help_text=(""),
)
next_payment_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Next Payment Date",
help_text=(""),
)
payment_made = models.BooleanField(
null=False,
blank=True,
default=False,
verbose_name="Is Payment Made",
help_text=(
""
),
)
subscription_date = models.DateTimeField(
null=True,
blank=True,
default=None,
verbose_name="Subscription Date",
help_text="",
)
Как вы видите, поле User - это OneToOneField
, а поле Subscription - foreign key
.
А вот мой сериализатор:
class SubscriptionInformationDetailSerializer(serializers.ModelSerializer):
class Meta:
model = SubscriptionInformation
fields = (
"id",
"user",
"subscription",
"subscription_type",
"next_payment_amount",
"next_payment_date",
"payment_made",
"subscription_date",
)
Я хочу вернуть сериализованную SubscriptionInformation с помощью следующего кода:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer
Но он выдает эту ошибку:
Traceback (most recent call last):
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\exception.py", line 42, in inner
response = get_response(request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 217, in _get_response
response = self.process_exception_by_middleware(e, request)
File "E:\Programming\project\venv\lib\site-packages\django\core\handlers\base.py", line 215, in _get_response
response = response.render()
File "E:\Programming\project\venv\lib\site-packages\django\template\response.py", line 109, in render
self.content = self.rendered_content
File "E:\Programming\project\venv\lib\site-packages\rest_framework\response.py", line 72, in rendered_content
ret = renderer.render(self.data, accepted_media_type, context)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\renderers.py", line 105, in render
allow_nan=not self.strict, separators=separators
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\json.py", line 28, in dumps
return json.dumps(*args, **kwargs)
File "C:\Python27\Lib\json\__init__.py", line 251, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\Lib\json\encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Python27\Lib\json\encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "E:\Programming\project\venv\lib\site-packages\rest_framework\utils\encoders.py", line 68, in default
return super(JSONEncoder, self).default(obj)
File "C:\Python27\Lib\json\encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: DetailSerializer(<Thing: Thing object>, read_only=True):
id = IntegerField(label='ID', read_only=True)
user = PrimaryKeyRelatedField(help_text='The user who subscribed.', queryset=User.objects.all(), validators=[<UniqueValidator(queryset=SubscriptionInformation.objects.all())>])
subscription = PrimaryKeyRelatedField(help_text='This is the subscription.', queryset=Subscription.objects.all())
subscription_type = ChoiceField(choices=((0, 'Monthly'), (1, 'Annual')), help_text='', label='Subscription Type', required=False, validators=[<django.core.validators.MinValueValidator object>, <django.core.validators.MaxValueValidator object>])
next_payment_amount = FloatField(help_text='', label='Subscription Plan Next Payment Amount', required=False)
next_payment_date = DateTimeField(allow_null=True, help_text='', label='Next Payment Date', required=False)
payment_made = BooleanField(help_text='', label='Is Payment Made', required=False)
subscription_date = DateTimeField(allow_null=True, help_text='', label='Subscription Date', required=False) is not JSON serializable
Я не мог понять, почему я не могу сериализовать это. Почему это не JSON serializable
Ок, Нет проблем с моделью и сериализатором. Мне просто нужно вернуть serializer.data
. Поэтому мой код должен выглядеть так:
subscription_information = SubscriptionInformation.objects.get(user_id=user.id)
serializer = SubscriptionInformationDetailSerializer(subscription_information, read_only=True)
return serializer.data