django - 如果隐藏了所有相关对象,则隐藏对象

时间:2013-12-02 17:43:02

标签: django django-models django-views django-templates

如果隐藏所有相关的object,如何隐藏objects

请让我解释一下。假设用户在一个线程(Thread_1)中有四条消息。并且他删除/隐藏来自该线程的所有消息。所以现在线程中没有消息(Thread_1)。如何隐藏没有要在模板中显示消息的线程(Thread_1)(其消息都是隐藏的)。

models.py

class Thread(models.Model):
    user = models.ManyToManyField(User)

class Message(models.Model):
    thread = models.ForeignKey(Thread)
    sent_date = models.DateTimeField(default=datetime.now)
    body = models.TextField()
    user = models.ForeignKey(User)


class HideMessage(models.Model):
    message = models.ForeignKey(Message)
    user = models.ForeignKey(User)

任何帮助都将不胜感激。谢谢!

修改

HTML:

    <div id="inbox">
        <div id="threads">
            {% for thread in all_threads %}
                <div class="thread">
                    <a href="/message/get/{{thread.id}}/">
                    <p>{{thread.id}}
                    {% for user in thread.user.all %}
                        {{user.username}},
                    {% endfor %}
                    </p>
                    </a>
                </div>
            <hr>
            {% endfor %}
        </div>
        <div id="conversation">
            {% for message in messages %}
                {% if message|is_hidden:user %}
                    <div class="messages">
                        <p>{{message.body}}</p>
                        <p>{{message.sent_date}}</p>
                        <p>-{{message.user}}</p>
                    <hr>
                    </div>
                {% endif %}
            {% endfor %}
        </div>
        <div class="clear_left"></div>
    </div>

修改

@login_required
def home(request):
    user = request.user

    # Get all the threads of that user
    threads = user.thread_set.all()

    # Order the threads by which thread recieved the latest message.
    order_threads_message = threads.annotate(max_sent_date=Max('message__sent_date')).order_by('-max_sent_date')

    # Get the recent thread
    recent_thread = order_threads_message[0]

    # Get the message of the recent thread
    recent_thread_messages = recent_thread.message_set.all()

    return render(request, 'base.html', {'all_threads':order_threads_message, 'messages':recent_thread_messages})

1 个答案:

答案 0 :(得分:0)

使用SQL,您可以一次性完成:

queryset = Thread.objects.extra(select={
    'msg_count': 'select count(*) from appname_message where appname_message.thread_id=appname_thread.id',
    'hidden_count': 'select count(*) from appname_hidemessage where appname_message.thread_id=appname_thread.id',
}, where=[
    'msg_count > hidden_count',
])

这将只选择消息 hidemessages 更多的线程。注意:将所有出现的 appname 替换为实际的应用名称。

但我必须注意,这是一个非常奇怪的建模。布尔标志不会足够吗?