1

我试图弄清楚人们将如何写评论以及如何存储它是为谁写的和谁写的。我想看看为一个人 UserProfile.Comments 写的评论...

任何人都可以帮助我吗?

模型.PY

class UserProfile(models.Model):
    comments =  models.ForeignKey("Comments", null=True, blank=True)


class Comments(models.Model):
    comment = models.CharField(max_length=500, null=False, blank=False)
    who_wrote = models.ForeignKey(User) 

VIEW.PY(我在这里卡住了)

def writecomment(request, username):
    if request.method == 'POST': 
        form = CommentForm(request.POST) 
        if form.is_valid():
            form.save(commit=False)
            form.user = request.user
            form.user_id = get_object_or_404(User, username=username).id
            #frm = form.save()

            usr = get_object_or_404(UserProfile, user = request.user)
            usr.Comments = form #append??
            usr.save()

   else:
        form = CommentForm(request.POST) 

    return render_to_response("writecomment.html", {"form": form}, context_instance=RequestContext(request))
4

1 回答 1

1

我相信您的模型可以稍微不同地创建以使这项任务更容易。只是有些事情要考虑。

  1. 每个用户可以有多个评论吗?UserProfile有一个字段叫做comments建议它可能是。这可能更好地建模为多对多字段。

  2. 应该UserProfile链接到用户吗?

  3. 似乎Comments可能需要支持 2 个用户,一个来自用户和一个到用户。


class UserProfile(models.Model):
     user = models.OneToOneField(User) # each user can have exactly 1 profile
     comments = models.ManyToManyField(Comment) # each user can have mutilple comments


class Comment(models.Model):
    text = models.CharField(max_length=500, null=False, blank=False)
    to = # shoudl this be foreign key or many to many?
    # can a comment reference multiple users or just one user or no user?

通过上述更改,向用户或用户获取评论变得更加容易

于 2013-03-26T13:14:02.600 回答