I have two models , Customer and Purchase. I want to return the last store that the customer purchased from and order on this.
I can successfully show this list, showing last store the Customer purchased from, and being able to order on store name, using the following models, query/subquery.
# models
class Customer(models.Model):
name = models.CharField(max_length=30)
class Purchase(models.Model):
store = models.CharField(max_length=30)
amount = models.DecimalField(decimal_places=2,max_digits=6)
customerID = models.ForeignKey(Customer, on_delete=models.CASCADE,
related_name='purchases')
order_date = models.DateField()
#viewset
#subquery
purchase_qs = Purchase.objects.filter(customerID=OuterRef("pk")).order_by("-order_date")
queryset = Customer.objects.all().annotate(last_purchase=Subquery(purchase_qs.values('store')[:1]))
ordering_fields = ['last_purchase']
My Current Output for Customers who have zero Purchases is.
"last_purchase":null
I want to have
"last_purchase":""