2011-09-27 95 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