如何从查询中插入值到另一个表字段?

问题描述 投票:-1回答:1

在我的模型上有一个表,名为 "订单"。

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)

而在pgadmin 4上,我做了如下查询

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

它创建了一个下面的表格

enter image description here

如何在Pgadmin 4上导入上次购买表上的客户表字段下面的last_purchase表内,?

如下图所示。


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

django postgresql django-models pgadmin-4
1个回答
0
投票

这应该可以了。把这个放在你的模型中

@property
def last_purchase(self):
    return Order.objects.get(customer_id=self.id).Last_purchase
© www.soinside.com 2019 - 2024. All rights reserved.