]>": "Booking.contact" 必须是 "Contact" 实例,django,django-models"/>

首页 > 解决方案 > 无法分配“]>": "Booking.contact" 必须是 "Contact" 实例

问题描述

我有一个问题,我创建了一个表单,用户可以在其中预订(详细查看)独特产品。所以一个用户可以有多个预订。使用的表格包含电子邮件和用户名。这种形式在我detail.html的包含变量中。

{% include 'store/list.html' with list_title=name %}

所以,当我运行我的服务器时,转到预订页面,输入用户名,电子邮件并提交,我有一个错误,而不是重定向到另一个页面。

模型.py

from django.db import models
    class Contact(models.Model):
        email = models.EmailField(max_length=100)
        name = models.CharField(max_length=200)

        def __str__(self):
            return self.name

    class Marque(models.Model):
        name = models.CharField(max_length=200, unique=True)

        def __str__(self):
            return self.name


    class Model(models.Model): #Plusieurs models pour une marque
        reference = models.IntegerField(null=True)
        created_at = models.DateTimeField(auto_now_add=True)
        available = models.BooleanField(default=True)
        name = models.CharField(max_length=200)
        picture = models.URLField()
        marque = models.ForeignKey(Marque, on_delete=models.CASCADE)

        def __str__(self):
            return self.name

    class Booking(models.Model): #plusieurs réservation pour un contact
        created_at = models.DateTimeField(auto_now_add=True)
        contacted = models.BooleanField(default=False)
        marque = models.OneToOneField(Marque, on_delete=models.CASCADE)
        model = models.OneToOneField(Model, on_delete=models.CASCADE)
        contact = models.ForeignKey(Contact, on_delete=models.CASCADE)

        def __str__(self):
            return self.contact.name

视图.py

   ...
def detail(request, model_id):
    model = get_object_or_404(Model, pk=model_id)
    #marques = [marque.name for marque in model.marque.all()]
    #marques_name = " ".join(marques)
    if request.method == 'POST':
        email = request.POST.get('email')
        name = request.POST.get('name')

        contact = Contact.objects.filter(email=email)
        if not contact.exists():
            #If a contact is not registered, create a new one
            contact = Contact.objects.create(
                email = email,
                name = name
            )
        #If no album matches the id, it means the form must have been tweaked
        #So returning a 404 is the best solution
        model = get_object_or_404(Model, pk=model_id)
        booking = Booking.objects.create(
            contact = contact,
            model = model
        )

        #Make sure no one can book the model again
        model.available = False
        model.save()
        context = {
        'model_name': model.name
        }
        return render(request, 'store/merci.html', context)

    message = "Le model est {}. Conçu par la marque {}".format(model.name, model.marque)
    context = {
    "model_name" : model.name,
    "model_marque" : model.marque,
    "model_id": model.id,
    "thumbnail" : model.picture
    }

    return render(request, 'store/detail.html', context)

detail.html中的search_form.html

<div class="container">
  <div class="col-lg-12 detail-separator">
    <form class="col-md-6 col-md-offset-3 text-center" action="{% url 'store:search' %}" method="get" accept-charset="utf-8">
      <div class="form-group">
        <label for="searchForm">Chercher un Model</label>
        <input id="searchForm" class="form-control" name="query">
      </div>
      <span class="help-block" id="helpBlock">Trouvez le model de voiture de vos rêves !</span>
    </form>
  </div>
</div>

标签: djangodjango-models

解决方案


您联系查询返回一个查询集:

contact = Contact.objects.filter(email=email)

然后,您尝试像使用contact单个Contact对象一样使用它:

booking = Booking.objects.create(
    contact = contact,
    model = model
)

这就是为什么 Django 抱怨它得到的是 aQueryset而不是Contact.

Contact即使查询集只包含一个对象,您也需要选择一个。例如

contacts = Contact.objects.filter(email=email)
if contacts.exists():
    contact = contacts[0]
else:
    #If a contact is not registered, create a new one
    contact = Contact.objects.create(
        email = email,
        name = name
    )

或者,最好:

try:
    contact = Contact.objects.get(email=email)
except DoesNotExist:
    contact = Contact.objects.create(
        email = email,
        name = name
    ) 

推荐阅读