Как получить отдельный список имен из списка консультаций и показать только последнюю консультацию в Django?

Я хочу получить уникальный список имен клиентов с последней датой консультации.

Я определил эти модели в моем файле models.py, используя mySQL как мою базу данных:

class Customer(models.Model):
  class ContactChoice(models.IntegerChoices):
    DO_NOT_CONTACT = 0
    EMAIL = 1
    TXT_SMS_VIBER = 2

  mobile_num = models.CharField('Mobile Number', max_length=10, unique=True,)
  email_add = models.EmailField('Email', max_length=150, unique=True,)
  last_name = models.CharField('Last Name', max_length=30,)
  first_name = models.CharField('First Name', max_length=30,)
  contact_for = models.CharField('Contact For', max_length=60,)
  contact_on = models.IntegerField('Contact Using', choices=ContactChoice.choices, default=0,)
  customer_consent = models.BooleanField('With Consent?', default=False,)

  def __str__(self):
    return self.last_name + ', ' + self.first_name

class Consultation(models.Model):
  consultation_date = models.DateTimeField('Date of Consultation', default=now)
  customer = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1)
  concern = models.ForeignKey(SkinConcern, on_delete=models.SET_DEFAULT, default=1)
  consultation_concern = models.CharField('Other Concerns', max_length=120, null=True,)
  product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1)
  user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default=1)
  store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT, default=1)
  consultation_is_active = models.BooleanField('Is Active', default=True)

  def __str__(self):
    return self.customer.last_name + ", " + self.customer.first_name

В моем файле views.py у меня есть следующее для страницы Консультации:

distinct = Consultation.objects.values('customer').annotate(consultation_count=Count('customer')).filter(consultation_count=1)
consults = Consultation.objects.filter(customer__in=[item['customer'] for item in distinct])

Как уже упоминалось, я ожидал получить уникальный список имен клиентов с их последними датами консультаций. Этот код приводит к тому, что отображается только 1 запись.

Можете ли вы указать мне правильное направление для этого? Заранее спасибо! :)

Как я вижу, то, что вы сейчас делаете, - это собираете всех клиентов, у которых была только одна консультация. Это не даст того, что вы хотите.

Я считаю, что для этого можно использовать метод latest(): https://docs.djangoproject.com/en/4.1/ref/models/querysets/#latest

Это непроверенный код, но вы можете сделать что-то вроде этого:

# gather all the customers
customers = Customer.objects.all()

# for every customer, get their latest consultation date, using the .latest() function
for customer in customers:
    try:
        latest_consultation = Consultation.objects.filter(customer=customer).latest('consultation_date')
        latest_consultation_date = latest_consultation.consultation_date
    except Consultation.DoesNotExist:
        latest_consultation_date = None

    customer.latest_consultation_date = latest_consultation_date

затем вы можете зациклиться на нем следующим образом:

for customer in customers:
    if customer.latest_consultation_date:
        print(customer.latest_consultation_date)
Вернуться на верх