django模特的谁和谁

时间:2013-03-26 13:06:34

标签: python django django-models django-views

我正在试图弄清楚人们如何写评论以及如何存储它的写作和写作者。我希望看到为一个人写的评论UserProfile.Comments ...

任何人都可以帮助我吗?

MODELS.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))

1 个答案:

答案 0 :(得分:1)

我相信您的模型可能会有所不同,以使此任务更容易。只是要考虑一些事情。

  1. 每位用户都可以有多条评论吗? UserProfile有一个名为comments的字段,表明它可能是。这可能更好地建模为多对多的字段。

  2. UserProfile是否应该链接到用户?

  3. 似乎Comments可能需要支持2个用户,包括用户和用户。


  4. 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?
    

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