【问题标题】:How to insert values from a query to another table field?如何将查询中的值插入另一个表字段?
【发布时间】:2020-09-03 08:31:59
【问题描述】:

我的模型下面有一个表格,称为订单

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 表中的以下客户表字段中导入最后一次购买表?

如下图,


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

【问题讨论】:

    标签: django postgresql django-models pgadmin-4


    【解决方案1】:

    应该这样做。把它放在你的模型中

    @property
    def last_purchase(self):
        return Order.objects.get(customer_id=self.id).Last_purchase
    

    【讨论】:

    • 但是我不是必须先从查询编辑器将 Last_purchase 字段导入到订单表中吗?
    • 这将为表格提供字段 last_purchase 并通过 Django 中的客户 ID 获取正确的 Last_purchase 日期
    猜你喜欢
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2014-10-21
    相关资源
    最近更新 更多