#django #forms #view #updates
Вопрос:
У меня есть форма для добавления встреч. Я хотел бы обновить поле в другой таблице во время отправки. Позвольте мне проиллюстрировать:
модель учетных записей (пользовательская модель пользователя)
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_patient после is_valid(), что-то вроде:
patient = Appointment.objects.filter(user=appoint_user).count() if patient gt; 0: patient.user__is_patient = 'Patient' patient.save()
Как я могу получить доступ к 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() gt; 0: patient[0].user.is_patient = 'Patient' patient.user.save() else: form.save()
Комментарии:
1. как выглядят модели назначений ?
2. Спасибо за комментарий! Я обновил сообщение с моделью встреч.
Ответ №1:
попробуйте это
patients = Appointment.objects.filter(user=appoint_user) if patients.count() gt; 0: for patient in patients: patient.user.is_patient = 'Patient' patient.user.save()
или
patients = Appointment.objects.filter(user=appoint_user) if patients.count() gt; 0: appoint_user.is_patient = 'Patient' appoint_user.save()
Комментарии:
1. Я понимаю
'QuerySet' object has no attribute 'user'
, я пытался так, я обновил сообщение.2. @paniklas ты написал именно то, что я написал здесь ?
3. @paniklas у вас опечатка, измените это
patient.user.save()
наpatient[0].user.save()
4. @paniklas это работает ?
5. К сожалению, не обновлено :(. У меня есть
lt;QuerySet [lt;Appointment: mariasakka@gmail.comgt;, lt;Appointment: mariasakka@gmail.comgt;, lt;Appointment: mariasakka@gmail.comgt;, lt;Appointment: mariasakka@gmail.comgt;, lt;Appointment: mariasakka@gmail.comgt;, lt;Appointment: mariasakka@gmail.comgt;]gt;
, но is_patient не обновлен, все еще «Новый пациент».