-1

I have a table below on my models called orders

class Order(models.Model):

    customer = models.ForeignKey(Customer, null=True, on_delete= models.SET_NULL)
    product = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=200, null=True, choices=STATUS)
    note = models.CharField(max_length=1000, null=True)
    stock = models.CharField(max_length=200, null=True)
    min_stock = models.CharField(max_length=200, null=True)

And on pgadmin 4 I have made an query below

SELECT customer_id, MAX(date_created) AS "Last_purchase" FROM public.accounts_order GROUP BY customer_id;

Which created an table below

enter image description here

How can I import the last purchase table on the customers table field below within the last_purchase table, on Pgadmin 4?

As shown below,


class Customer(models.Model):



    title = models.CharField(max_length=200, null=True, choices=TITLE)
    first_name = models.CharField(max_length=200, null=True)
    middle_name = models.CharField(max_length=200, blank=True,default='')
    last_name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    country = CountryField()
    birth_year = models.CharField(max_length=4, null=True)
    gender = models.CharField(max_length=200, null=True, choices=GENDER)
    email = models.CharField(max_length=200, null=True)
    password = models.CharField(max_length=200, null=True)
    status = models.CharField(max_length=200, null=True,choices=STATUS)
    date_created = models.DateTimeField(auto_now=True, null=True)
    profile_pic = models.ImageField(null=True, blank=True, default='images/default.png')
    role = models.CharField(max_length=200, null=True, choices=ROLE)
    last_purchase = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.first_name

enter image description here

hg

kamcoder
  • 75
  • 7

1 Answers1

0

This should do it. Put this in your model

@property
def last_purchase(self):
    return Order.objects.get(customer_id=self.id).Last_purchase
Harben
  • 1,802
  • 1
  • 11
  • 16
  • But don't I have to import Last_purchase field on to the order table from the query editor first? – kamcoder May 17 '20 at 15:57
  • This will give the field last_purchase for the table and get the correct Last_purchase date by customer id in Django – Harben May 17 '20 at 16:09