Django не передает модели ForeignKey в JSON
У меня есть модель Comment, которая имеет 2 атрибута, ссылающихся на Forum модели и Profile модели как внешний ключ, который я пытаюсь сериализовать в JSON. Но когда я пытаюсь использовать сериализаторы, JSON объект моего foreignkey attrs возвращает Null. Я не знаю почему, поскольку это кажется нормальным, когда я отлаживаю код и печатаю объект перед сохранением в форме.
МОДЕЛИ:
class Comment(models.Model):
message = models.TextField()
forum_creator_username = models.CharField(max_length=200, null=True, blank=True)
forum_creator = models.ForeignKey(Forum, on_delete=models.CASCADE, blank = True, null = True)
comment_creator = models.ForeignKey(Profile, on_delete=models.CASCADE, blank = True, null = True)
created_at = models.CharField(max_length=50,null=True, blank=True)
comment_creator_username = models.CharField(max_length=200, null=True, blank=True)
creator_image = models.ImageField(
blank=True,
null=True,
default="profiles/default-user_pfzkxt",
)
Просмотров:
def index(request, id):
forums = Forum.objects.all().values()
form = CommentForm(request.POST)
response={}
if request.method == "POST":
if (form.is_valid):
print(form.is_valid)
print(form.is_valid())
add_comment = form.save(commit=False)
add_comment.forum = Forum.objects.get(pk=id)
add_comment.comment_creator = Profile.objects.get(user = request.user.id)
add_comment.forum_creator = Forum.objects.get(pk=id)
add_comment.forum_creator_username = add_comment.forum_creator.creator.username
add_comment.comment_creator_username = add_comment.comment_creator.username
add_comment.creator_image = add_comment.comment_creator.profile_image
add_comment.created_at = datetime.now().strftime("%A, %d %B %Y, %I:%M %p")
add_comment.save()
return HttpResponseRedirect(request.path_info)
response['form'] = form
Comment.forum_creator = Forum.objects.get(pk = id)
test = Comment.forum_creator = Forum.objects.get(pk = id)
print("TES FORUM:",test.id)
Comment.comment_creator = Profile.objects.get(user = request.user.id)
a = Comment.comment_creator
print("comment_reator adalah:",a)
print("TES", Comment.forum_creator, "comment:",Comment.comment_creator)
response['forum'] = Comment.forum_creator
return render(request, "comment_list.html", response)
def json_api(request):
comments = Comment.objects.all()
#here is where my comment_creator become null
for comment in comments:
print(comment.comment_creator)
response = {'comments' : comments.values()}
print(response)
data = serializers.serialize('json', Comment.objects.all())
return HttpResponse(data, content_type="application/json")
Результат примера JSON из кода выше:
[
{
"model": "comment.comment",
"pk": 20,
"fields": {
"message": "tes comment",
"forum_creator_username": "admin",
"forum_creator": null,
"comment_creator": null,
"created_at": "Saturday, 30 October 2021, 12:55 AM",
"comment_creator_username": "admin",
"creator_image": "images/media/profiles/alhikam_mugys8"
}
},
{
"model": "comment.comment",
"pk": 21,
"fields": {
"message": "halo",
"forum_creator_username": "admin",
"forum_creator": null,
"comment_creator": null,
"created_at": "Saturday, 30 October 2021, 11:31 AM",
"comment_creator_username": "admin",
"creator_image": "images/media/profiles/alhikam_mugys8"
}
},
{
"model": "comment.comment",
"pk": 22,
"fields": {
"message": "tes",
"forum_creator_username": "admin",
"forum_creator": null,
"comment_creator": null,
"created_at": "Saturday, 30 October 2021, 11:32 AM",
"comment_creator_username": "admin",
"creator_image": "images/media/profiles/alhikam_mugys8"
}
},
{
"model": "comment.comment",
"pk": 23,
"fields": {
"message": "tes",
"forum_creator_username": "admin",
"forum_creator": null,
"comment_creator": null,
"created_at": "Saturday, 30 October 2021, 11:33 AM",
"comment_creator_username": "admin",
"creator_image": "images/media/profiles/alhikam_mugys8"
}
},
{
"model": "comment.comment",
"pk": 24,
"fields": {
"message": "tes ke dua",
"forum_creator_username": "admin",
"forum_creator": null,
"comment_creator": null,
"created_at": "Saturday, 30 October 2021, 11:34 AM",
"comment_creator_username": "admin",
"creator_image": "images/media/profiles/alhikam_mugys8"
}
}
]
* Заметьте, что на Views я назначил имя_создателя_комментария следующим образом:
add_comment.comment_creator_username = add_comment.comment_creator.username
и он также отлично работает с JSON. Так что я полагаю, что единственная проблема заключается в том, как я могу передать мои модели ForeingKey в JSON? Заранее спасибо