Django & SQLite.db -数据被复制

pgvzfuti  于 2023-02-05  发布在  SQLite
关注(0)|答案(2)|浏览(134)

我在Django框架中创建了两个模型,第一个模型负责保存邮件,第二个模型负责保存消息,所有邮件和消息都保存在SQLite.db中,但是当我多次添加相同的邮件时,数据库创建了一个新记录,我不我没有一个线索,我如何管理保存数据检索多封电子邮件具有相同的名称,然后通过他们作为一个共同的电子邮件到HTML模板与所有分配给他们的信息。

    • 示例:**我从test@test.com发送了3条消息。消息:["嗨"、"你好"、"您好"]以及来自www.example.com ["嗨"] DB表的一条消息:user@user.com ['Hi'] DB table:
    • 实际结果:**3条记录
  1. www.example.com test@test.com| 'Hi'
  2. www.example.comtest@test.com| 'Hello'
  3. www.example.comtest@test.com| 'Bonjour'
  4. www.example.com user@user.com| 'Hi'
    型号:
class Email(models.Model):
    """The guest's email."""
    text = models.EmailField(max_length=100)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

class EmailMessage(models.Model):
    """The guest's message."""
    email = models.ForeignKey(Email, on_delete=models.CASCADE)
    message = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.message

然后我想将所有数据传递给HTML模板以显示它们:网址:/电子邮件

def emails(request):
    """Show all emails."""
    emails = Email.objects.order_by('date_added')
    context = {'emails': emails}
    return render(request, 'home/emails.html', context)

HTML部分:(我想在此页面上只显示电子邮件,而不显示消息,当我单击每封电子邮件时,用户应该被重定向到另一个页面,显示分配给特定电子邮件的所有消息。

<h1>Emails</h1>

<ul>
    {% for email in emails %}
        <li>
            <a href="{% url 'home:email' email.id %}">{{ email.text }}</a>
        </li>
    {% empty %}
        <li>No emails have benn added yet.</li>
    {% endfor %}
</ul>

网址:/email/电子邮件ID

def email(request, email_id):
    """Show a single email and all its messages."""
    email = Email.objects.get(id=email_id)
    messages = email.emailmessage_set.order_by('-date_added')
    context = {'email': email, 'messages': messages}
    return render(request, 'home/messages.html', context)

模板:

<h1>Email: {{ email }}</h1>

<ul>
    {% for message in messages %}
        <li>
            <p>{{ message.date_added|date:'M d, Y H:i' }}</p>
            <p>{{ message|linebreaks }}</p>
        </li>
    {% empty %}
        <li>No emails have benn added yet.</li>
    {% endfor %}
</ul>

但最终的结果是:

  1. www.example.com test@test.com
    消息_1:嗨
  2. www.example.com test@test.com
    消息_1:您好
  3. www.example.com test@test.com
    消息_1:您好
  4. www.example.com user@user.com
    消息_1:嗨
    • 预期成果:**
  1. www.example.com test@test.com
    消息_1:嗨
    消息_2:您好
    消息_3:您好
  2. www.example.com user@user.com
    消息_1:嗨


!!!当我点击特定的电子邮件时,消息可用!因此,当用户点击特定的电子邮件时,他将被重定向到包含所有消息的另一个页面。

    • 问题是如何处理?我应该修改HTML(javascript)视图功能还是创建模型**?哪种方法最能使我的页面更稳定?
qc6wkl3g

qc6wkl3g1#

要按电子邮件对邮件进行分组,您需要修改view函数,以根据电子邮件对邮件进行分组。以下是view函数的示例代码:

def emails(request):
    """ Show all emails with grouped messages."""
    emails = Email.objects.order_by('date_added').values('email').annotate(message_count=Count('email'))
    messages = Message.objects.order_by('email') # guessing that you message is saved in this model.
    context = {'emails': emails, 'messages': messages}
    return render(request, 'home/emails.html', context)

html文件

<h1>Emails</h1>
    
    <ul>
        {% for email in emails %}
            <li>{{ email.email }}</li>
            <ul>
                {% for message in messages %}
                    {% if email.email == message.email %}
                        <li>message_{{ forloop.counter }}: {{ message.text }}</li>
                    {% endif %}
                {% endfor %}
            </ul>
        {% empty %}
            <li>No emails have been added yet.</li>
        {% endfor %}
    </ul>
nnvyjq4y

nnvyjq4y2#

我们可以通过以下方式传递EmailMessage

def emails(request):
    messages = EmailMessage.objects.select_related('email').order_by('date_added')
    context = {'messages': messages}
    return render(request, 'home/emails.html', context)

您可以通过电子邮件地址**{% regroup … %}**[Django-doc]发送消息:

<h1>Emails</h1>

<ul>
    {% regroup messages by email.text as message_group %}
    {% for email, messages in message_group %}
        <li>
            {{ email }}:
            <ul>
            {% for message in messages %}
                <a href="{% url 'home:email' message.pk %}">{{ message.message }}</a>
            {% endfor %}
            </ul>
        </li>
    {% empty %}
        <li>No emails have been added yet.</li>
    {% endfor %}
</ul>

相关问题