在 Django 中加入两个模型后如何处理 views.py?

How to handle views.py after joining two models in Django?

这里我有两个模型,第一个是 Contact,第二个模型是 Sent_replies。那么,我应该在 views.py 中做什么,以便如果有人在 Contact 中发送响应,数据也会在 Sent_replies 型号

models.py

class Contact(models.Model):
    message_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    email = models.CharField(max_length=100)
    phone = models.CharField(max_length=100)
    comment = models.TextField(max_length=100)
    date = models.DateField()

    def __str__(self):
        return self.name
class Sent_replies(models.Model):
    message_sender = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True)
    def __str__(self):
        return self.message.name

views.py

def contact(request):
    if request.method == "POST":
        name = request.POST.get("name")
        email = request.POST.get("email")
        phone = request.POST.get("phone")
        comment = request.POST.get("comment")
        if name != "":
            contact = Contact(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
            contact.save()
            messages.success(request, 'Your response has been submitted successfully!!!')
    return render(request, 'contact.html')

有很多方法可以做到这一点,仅在您的视图中逻辑或创建一个信号来处理它。

你的逻辑 views.py:

if name != "":
     contact = Contact.objects.create(name=name, email=email, phone=phone, comment=comment, date=datetime.today())
     Sent_replies.objects.create(message_sender=contact)

在您的 models.py 文件中使用 signal

from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Contact)
def add_reply(sender, instance, created, **kwargs):
    if created == True:
       Sent_replies.objects.create(message_sender=instance)