我正在尝试将评论模型与 auth用户模型的用户名字段相关联。
这是代码
from django.contrib.auth.models import User
from django.db import models
from urllib.parse import urlparse
class Posts(models.Model):
title = models.CharField(max_length=200)
url = models.URLField()
points = models.IntegerField(default=0)
moderator = models.ForeignKey(User, related_name="moderated_stories")
voters = models.ManyToManyField(User, related_name="liked_stories", blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
@property
def domain(self):
return urlparse(self.url).netloc
def __str__(self):
return self.title + " by " + self.moderator.username
class Meta:
verbose_name_plural = "stories"
class Comments(models.Model):
comment = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, related_name="commented_on", to_field="username")
commented_on = models.ForeignKey(Posts, related_name="comments")
def __str__(self):
return self.comment + " by " + self.user
class Meta:
verbose_name_plural = "comments"
但是在执行查询时会出现以下错误:
>>> post = Posts.objects.get(id=2)
>>> post.comments.all()
django.contrib.auth.models.DoesNotExist: User matching query does not exist.
但是当我执行查询以序列化数据时它可以工作
>>> serializers.serialize('json', post.comments.all())
'[{"model": "news.comments", "pk": 1, "fields": {"comment": "Thanks for sharing
the link :)", "commented_on": 2, "created_at": "2015-09-30T06:01:40.201Z", "user
": 1}}, {"model": "news.comments", "pk": 2, "fields": {"comment": "this is what
i was looking for...!", "commented_on": 2, "created_at": "2015-09-30T06:02:17.4
97Z", "user": 4}}, {"model": "news.comments", "pk": 3, "fields": {"comment": "th
anks for sharing !", "commented_on": 2, "created_at": "2015-09-30T06:02:43.971Z"
, "user": 3}}]'
但序列化数据仍然包含用户的 PK ,而不是用户名。 这段代码出了什么问题?