Django无法解压缩不可编辑的配置文件对象错误

2024-09-28 01:30:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一个用户创建多个appointment,每当我这样做时,都会出现此错误

Traceback (most recent call last):
  File "C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\core\models.py", line 47, in create_appointment
    appointment,created = cls.objects.get_or_create(patient=patient,hospital=hospital)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 573, in get_or_create
    return self.get(**kwargs), False
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 436, in get
    num if not limit or num < limit else 'more than %s' % (limit - 1),

During handling of the above exception (get() returned more than one Appointment -- it returned 2!), another exception occurred:
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\dashboard\views.py", line 31, in bookapp
    Appointment.create_appointment(hospital,request.user.profile)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\core\models.py", line 49, in create_appointment
    appointment = cls.objects.filter(patient).order_by('id')
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 942, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 962, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, *args, **kwargs)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\query.py", line 969, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\sql\query.py", line 1358, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\sql\query.py", line 1380, in _add_q
    split_subq=split_subq, check_filterable=check_filterable,
  File "C:\Users\USER\Desktop\cvbn\djangovueto\sert\lib\site-packages\django\db\models\sql\query.py", line 1255, in build_filter
    arg, value = filter_expr

Exception Type: TypeError at /dashboard/connect/add/2/
Exception Value: cannot unpack non-iterable Profile object

目前我只能创建一个约会我希望用户能够创建多个AppPoints。但是我可以在我的管理面板中为一个用户与另一个用户创建多个约会,没有任何问题。错误似乎来自我的get\u或\u create方法。这是具有该方法的models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    last_name = models.CharField(max_length=100, blank=True)
    email = models.EmailField(max_length=150)
    title = models.CharField(max_length=255, null=True)
    margin = models.FloatField(default=20, null=True)
    amount = models.FloatField(default=20, null=True)
    country = models.CharField(max_length=255, null=True)
    phonenumber = models.CharField(max_length=20, null=True)
    appointment_with = models.ManyToManyField(User, related_name='appontment_with', blank=True)


    def __str__(self):
        return self.user.username
    
    def get_hospitals(self):
        return self.hospitals.all()





STATUS_CHOICES = (
    ('book', 'book'),
    ('approved', 'approved'),
)
class Appointment(models.Model):
    patient = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='patientt', null=True)
    hospital = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='hospital', null=True)
    created = models.DateTimeField(auto_now_add=True)
    
    status = models.CharField(max_length=50, choices=STATUS_CHOICES, default='none')

    @classmethod
    def create_appointment(cls, hospital,patient):
        try:
            appointment,created = cls.objects.get_or_create(patient=patient,hospital=hospital)
        except cls.MultipleObjectsReturned:
            appointment = cls.objects.filter(patient).order_by('id')

        appointment.hospital.appointment_with.add(patient.user)

我正在添加我的URL.py和视图

from django.urls import path, re_path
from .views import dashboard, profile, bookapp, acceptapp

urlpatterns = [
    path('', dashboard, name='dashboard'),
    path('profile', profile, name='profile'),
    re_path(r'^connect/(?P<operation>.+)/(?P<pk>\d+)/$',
        bookapp, name='bookapp'),
]

views.py

def bookapp(request, operation, pk):
     hospital = Profile.objects.get(pk=pk)
     
     if operation == 'add':
        Appointment.create_appointment(hospital,request.user.profile)
        
        return HttpResponse('You have booked an appointment')

Tags: djangoinpygetmodelsliblineusers
2条回答

这里的问题是,您应该将字典类型或关键字参数发送到appointment = cls.objects.filter(patient).order_by('id')中的queryset筛选器,而不是配置文件对象(如果您确定patient是Appointment模型的实例)。您应该将其更改为类似appointment = cls.objects.filter(patient=patient).order_by('id')appointment = cls.objects.filter(patient_id=patient.id).order_by('id')的内容。作为Django例外(在您的问题中提到),我认为更改File"C:\Users\USER\Desktop\cvbn\djangovueto\vuewe\aview\core\models.py", line 49, in create_appointment行(模型中的第49行)将解决您的问题。最后,我应该说create_约会中的约会类型不同(其中一个是model对象,另一个是queryset对象),所以也不要忘记更改它们,因为如果视图发生异常,那么appointment.hospital.appointment_with.add(patient.user)行也会引发错误

appointment,created = cls.objects.get_or_create(patient=patient,hospital=hospital)行返回2个对象,get只等待1个对象。您应该确保Appointment实例与patienthospital(一起)具有唯一性。如果您不能确定这意味着多个实例可以具有相同的patienthospital,那么您不能使用get方法

相关问题 更多 >

    热门问题