Django 如何将查询中的值插入另一个表字段?
我有一张关于我的模型的表格,叫做订单Django 如何将查询中的值插入另一个表字段?,django,postgresql,django-models,pgadmin-4,Django,Postgresql,Django Models,Pgadmin 4,我有一张关于我的模型的表格,叫做订单 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(a
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;
它在下面创建了一个表
如何在Pgadmin 4上的last_purchase表中的customers表字段中导入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
hg这应该可以。把这个放在你的模型里
@property
def last_purchase(self):
return Order.objects.get(customer_id=self.id).Last_purchase
但是我不是必须首先从查询编辑器将Last_purchase字段导入订单表吗?这将为表提供Last_purchase字段,并通过Django中的客户id获得正确的Last_purchase日期