【问题标题】:Update field on another table when submitting form - django提交表单时更新另一个表上的字段 - django
【发布时间】:2022-01-04 07:50:04
【问题描述】:

我有一个添加约会的表格。我想在提交期间更新另一个表中的字段。让我举例说明:

账户模型(自定义用户模型)

class Account(AbstractBaseUser):

    patient_status = (     
        ('No Patient', _('No Patient')),
        ('New Patient', _('New Patient')),
        ('Patient', _('Patient')),
    )

    first_name = models.CharField(_('First Name'), max_length=50)
    last_name = models.CharField(_('Last Name'), max_length=50)
    username = models.CharField(_('Username'), max_length=50, unique=True)
    ...
    # required
    is_patient = models.CharField(_('Patient'), max_length=20, choices=patient_status)
    ...

views.py 添加约会:

def add_appointment(request):
    form = AddAppointmentForm(request.POST or None)
    
    if request.method == 'POST':
        if form.is_valid():
            appoint_user = form.cleaned_data.get('user')
            appoint_seat = form.cleaned_data.get('seat')
            appoint_start_appointment = form.cleaned_data.get('start_appointment')
            appoint_end_appointment = form.cleaned_data.get('end_appointment')
            
            # If Appointment already exist 
            if Appointment.objects.filter(user=appoint_user, seat=appoint_seat, start_appointment=appoint_start_appointment, end_appointment=appoint_end_appointment).exists():
                messages.warning(request, "This appointment already exists.")

            else:
                form.save()

                messages.success(request, 'Appointment was added successfully!')
                return redirect('appointments:add_appointment')
    else:
        form = AddAppointmentForm()

我想在 is_valid() 之后更新 is_patient,类似于:

patient = Appointment.objects.filter(user=appoint_user).count()
if patient > 0:
  patient.user__is_patient = 'Patient'
  patient.save()

如何从 Account 的表中访问 is_patient 以进行更新,以及在视图中放置代码的正确位置是什么?

更新约会模型

class Appointment(models.Model):
    
    APPOINTMENT_STATUS = (
        ('New', _('New')),
        ('Finished', _('Finished')),
        ('Rescheduled', _('Rescheduled')),
        ('Cancelled', _('Cancelled')),
        ('Notshow', _('Notshown')),
    )

    DURATION = (
        ('Notstarted', _('Not Started')),
        ('Checkin', _('Check In')),
        ('TransferToSeat', _('Transfer to Seat')),
        ('Completed', _('Completed')),
    )

    user = models.ForeignKey(Account, on_delete=models.CASCADE)
    seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True)
    start_appointment = models.DateTimeField(default=timezone.now, blank=True)
    end_appointment = models.DateTimeField(default=timezone.now, blank=True)
    name = models.CharField(max_length=255)
    appointment_notes = models.TextField(_('Appointment Notes'), max_length=1500, null=True, blank=True)
    status = models.CharField(_('Appointment Status'), max_length=20, choices=APPOINTMENT_STATUS, default='New')
    duration = models.CharField(_('Duration'), max_length=20, choices=DURATION, default='Not Started')
    confirmed = models.BooleanField(_('Confirmed'), default=False)
    emailed = models.BooleanField(_('Emailed'), default=False)
    date_created = models.DateTimeField(_('Date Created'), auto_now_add=True)
    date_updated = models.DateTimeField(_('Date Updated'), auto_now=True)

Update添加代码后:

if request.method == 'POST':
        if form.is_valid():
            appoint_user = form.cleaned_data.get('user')
            appoint_seat = form.cleaned_data.get('seat')
            appoint_start_appointment = form.cleaned_data.get('start_appointment')
            appoint_end_appointment = form.cleaned_data.get('end_appointment')
            
            # If Appointment already exist 
            if Appointment.objects.filter(user=appoint_user, seat=appoint_seat, start_appointment=appoint_start_appointment, end_appointment=appoint_end_appointment).exists():
                messages.warning(request, "This appointment already exists.")

            else:
                patient = Appointment.objects.filter(user=appoint_user)
                if patient.count() > 0:
                    patient[0].user.is_patient = 'Patient'
                    patient.user.save()
                
                else:
                    form.save()

【问题讨论】:

  • 约会模型是什么样的?
  • 感谢您的评论!我已经用约会模型更新了帖子。

标签: django forms view updates


【解决方案1】:

试试这个

patients = Appointment.objects.filter(user=appoint_user)
if patients.count() > 0:
  for patient in patients:
      patient.user.is_patient = 'Patient'
      patient.user.save()

patients = Appointment.objects.filter(user=appoint_user)
if patients.count() > 0:
    appoint_user.is_patient = 'Patient'
    appoint_user.save()
  

【讨论】:

  • 我收到'QuerySet' object has no attribute 'user',我试过这样我已经更新了帖子。
  • @paniklas 你写的和我在这里写的完全一样吗?
  • @paniklas 你有错别字把这个patient.user.save()改成patient[0].user.save()
  • @paniklas 有效吗?
  • 很遗憾没有更新:(。我有<QuerySet [<Appointment: mariasakka@gmail.com>, <Appointment: mariasakka@gmail.com>, <Appointment: mariasakka@gmail.com>, <Appointment: mariasakka@gmail.com>, <Appointment: mariasakka@gmail.com>, <Appointment: mariasakka@gmail.com>]>but is_patient 没有更新,仍然是“新病人”。
猜你喜欢
  • 2017-08-17
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 2019-05-27
  • 2015-04-29
  • 2015-11-12
  • 1970-01-01
相关资源
最近更新 更多