如何在Django中连接表?

时间:2018-04-11 13:53:15

标签: python django

以下是我的models.py

class Topic(models.Model):
    name = models.CharField(max_length=30, unique=True)
    description = models.CharField(max_length=300)
    created_on = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(User, related_name='topic')
    def __str__(self):
        return self.name

class Question(models.Model):
    name = models.CharField(max_length=300, unique=True)
    img = models.CharField(max_length=100)
    topic = models.ForeignKey(Topic, related_name='question')
    created_by = models.ForeignKey(User, related_name='question')
    created_on = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.name

class Answer(models.Model):
    ans = models.TextField()
    img = models.CharField(max_length=100)
    created_by = models.ForeignKey(User, related_name='answer')
    created_on = models.DateTimeField(auto_now_add=True)
    ques = models.ForeignKey(Question, related_name='answer')
    def __str__(self):
        return self.ans

class Upvote(models.Model):
    upvote = models.BooleanField(default=False)
    upvote_by = models.ForeignKey(User, related_name='upvote')
    upvoted_on = models.DateTimeField(auto_now_add=True)
    ques = models.ForeignKey(Question, related_name='upvote')
    ans = models.ForeignKey(Answer, related_name='upvote')

class Comment(models.Model):
    comment = models.TextField()
    comment_by = models.ForeignKey(User, related_name='comment')
    commented_on = models.DateTimeField(auto_now_add=True)
    ques = models.ForeignKey(Question, related_name='comment')
    ans = models.ForeignKey(Answer, related_name='comment')

class Follow(models.Model):
    topic = models.ForeignKey(Topic, related_name='follow')
    user = models.ForeignKey(User, related_name='follow')

我正在尝试根据具有用户主题映射的下表获得问题和答案。

  • user_topic =从关注表中为用户提供主题
  • question =在topic = user_topic
  • 中提问
  • answer =在ques = question
  • 的地方回答

以下是我的views.py

def home(req):
    user_id = req.user.id
    follow = Follow.objects.filter(user = user_id).all()
    user_follow_topics = Topic.objects.filter(pk__in=follow).all()
    question = Question.objects.filter(topic__in=user_follow_topics).all()
    answer = Answer.objects.filter(ques__in=question).all()
    topic = Topic.objects.all()
    return render(req,'home.html',{'topic':topic,'user_follow_topic':user_follow_topics,'question':question,'answer':answer})

以下是我的home.html

<div class="container" id="cont">
        <div id="topicDiv" class="row">
            <input type="hidden" value="{%csrf_token%}" id="hid_csrf"/>
            {% for t in topic %}
            <h4 id="{{t.pk}}" class="topCls"><span class="badge badge-Info">{{t.name}}</span></h4>
            &nbsp;
            {% endfor %}
        </div>
    <br />
        <div class="" id="">
            {% for ans in answer %}
            <div id="feed">
                <div id="">
                    <h5><span class="">{{ans.ques.name}}</span></h5>
                </div>
                <div class="">
                    <h6><span class="">{{ans.ans}}</span></h6>
                </div>
            </div>
            <br />
            {% endfor %}
        </div>
</div>

1 个答案:

答案 0 :(得分:0)

也许我失去了一些东西)

PS:最好使用复数形式的related_name参数。

from django.db.models import Prefetch, Count

Question.objects.filter(
    topic__follow__user=request.user
).select_related(
    'topic', 'created_by'
).prefetch_relaed(
    Prefetch(
        'answer',
        queryset=Answer.objects.select_related('created_by').annotate(
            upvotes_count=Count('upvote')
        ).prefetch_related(
            Prefetch(
                'comment',
                queryset=Comment.objects.select_related('comment_by')
            )
        )
    ),
    Prefetch(
        'comment',
        queryset=Comment.objects.select_related('comment_by')
    ),
).annotate(
    upvotes_count=Count('upvote')
)