簡體   English   中英

Django如何從咨詢列表中獲取不同的姓名列表,並僅顯示最新咨詢?

[英]How to get distinct list of names from a consultation list, and show only latest consultation in 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM