2011-09-27 94 views
1

用户/审阅我是有点新的数据库设计,但我想创建三个表“用户”和“评论”和“主题”在Django的数据库。数据库设计在Django的数据库模型

我会尝试在这里详细解释一下:

例如,我在models.py用户,主题和审查模式。一个用户只能从其他用户为一个主题撰写一篇评论。

让我们说:迈克,约翰,彼得是三个用户。

迈克发布的 “Hello World” 主题。 John只能为主题“Hello World”撰写一篇评论,彼得也可以为此撰写一篇评论。约翰和彼得不能发表针对同一主题的其他评论(他们只能修改它)。如果迈克发表另一个话题,约翰和彼得可以发表新的话题的另一篇评论。相同的规则适用于其他用户。

请如果可以的话,请你提供这个问题的一些示例代码?非常感谢。

回答

1

如果您想了解如何设置您的models.py,请访问django文档,然后查看编写您的第一个应用程序(https://docs.djangoproject.com/zh/dev/intro/tutorial01 /)。它从头到尾编写你的第一个应用程序,你将学习系统如何工作。

如果你想要更多的细节为你的案件的范例,这里就是我会做。我可能会在视图/模板中处理这个问题,并使用Dajaxice调用数据库来提交/编辑审阅。如果存在当前用户的评论,则会显示数据,如果不存在,将会使用Dajax提交内容的空白条目。在该Dajax调用蟒蛇方法,你会尝试找到一个审查,如果在尝试添加一个新的存在,出了问题,你可以处理的错误,否则将被保存有目共睹。

例如,在models.py:

class User(models.Model): 
    name = models.CharField(max_length=128) 
    def __unicode__(self): 
     return self.name 

class Review(models.Model): 
    title = models.CharField(max_length=64) 
    message = models.TextField() 
    topic = models.ForeignKey(Topic) 
    user = models.ForeignKey(User) 
    def __unicode__(self): 
     return self.title 

class Topic 
    title = models.CharField(max_length=64) 
    message = models.TextField() 
    user = models.ForeignKey() 
    def __unicode__(self): 
     return self.title 

在views.py:

class Post(models.Model): # This is defined a model, but not part of the data layer, it really is view code. 
    topic = None 
    your_review = None 
    other_reviews = None 
    def __unicode__(self): 
     return '' 

def GetDetails(request): 
    posts =() # to be returned to and looped by the Template. 
    topics = Topic.objects.all().order_by('-posting_date') # posting_date descending. 

    for t in topics: 
     post = Post() 
     post.topic = t 
     post.your_review = Review.objects.filter(topic__id=t.id, user__id=<current_user_id>) 
     post.other_reviews = Review.objects.filter(topic__id=t.id, ~Q(user__id=<current_user_id>) 

     # Append to the posts array. 
     posts.append(post) 

    return render_to_response('index.htm', {'posts': posts}, context_instance=RequestContext(request)) 
在你的index.htm

{% if posts %} 
    {% for p in posts %} 
     <div> 
      <div class="title">{{ p.topic.title }}</div> 
      <div class="message">{{ p.topic.message }}</div> 
      <div class="other_reviews"> 
       {% if p.other_reviews %} 
        {% for r in p.other_reviews %} 
         <div class="review_title">{{ r.title }}</div> 
         <div class="review_message">{{ r.message }}</div> 
        {% endfor %} 
       {% endif %} 

       <div> 
        <input type="text" value="{% if p.your_review %}{{ p.your_review.title }}{% endif %}"> 
       </div> 
       <div> 
        <textarea>{% if p.your_review %}{{ p.your_review.message }}{% endif %}</textarea> 
       </div> 
      </div> 
     </div> 
    {% endfor %} 
{% endif %} 
+0

谢谢Furbeenator,这正是我想要什么,再次感谢。 – triston

+0

很高兴提供帮助。我在原始文章中做了一个嘘声,在GetDetails()中,我忘记了在设置post.topic之前声明post对象。我已经更新,使post.topic = t之前的类(上P)发布和声明post = Post()。 – Furbeenator