【问题标题】:django complex queries filter and create listdjango 复杂查询过滤和创建列表
【发布时间】:2017-08-30 23:13:57
【问题描述】:

类或模型

class Category(models.Model):

    category_name = models.CharField(max_length=50)
    company_name = models.CharField(max_length=50)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)


    def __unicode__(self):
        return self.category_name


class Product(models.Model):

    product_name = models.CharField(max_length=50)
    category = models.CharField(max_length=50)
    desc = models.CharField(max_length=120)
    company_name = models.CharField(max_length=50, default=None)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)


class ProductDetails(models.Model):

    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    batch = models.CharField(max_length=50)
    quantity = models.IntegerField()
    cost = models.FloatField(null=True, blank=True, default=None)
    mfg = models.DateTimeField()
    exp = models.DateTimeField()
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)


class product_barcode(models.Model):
    batch = models.ForeignKey(ProductDetails, on_delete=models.CASCADE)
    barcode = models.BigIntegerField()
    flag = models.IntegerField()
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)
    updated = models.DateTimeField(auto_now_add = False, auto_now = True)

1> 第一个任务 查找产品名称、成本、标志?使用 product_barcode 表的条形码值

类 S_history

class S_History(models.Model):
    barcode = models.CharField(max_length=500)
    email = models.CharField(max_length=100)
    timestamp = models.DateTimeField(auto_now_add = True, auto_now = False)

2> 如果 S_History.barcode=prodcut_barcode.barcode 则创建列表

S_History 表可能包含多个相同条码的条目

列表看起来像

[{"product_name":"fff","cost":"999"},{"product_name":"xxxwww","cost":"55"}]

【问题讨论】:

    标签: mysql django python-2.7 django-models


    【解决方案1】:

    1) 您的第一个查询将如下所示

     product_detail = product_barcode.objects.filter().values('flag', 'ProductDetails__cost', 'ProductDetails__product__product_name')
    

    2) 对于第二个查询,您需要 product_barcode 的对象 并使用

    product_detail = S_History.objects.filter(barcode=product_barcode.barcode )
    

    【讨论】:

    • 给出异常类型对象'product_barcode'没有属性'barcode'
    • 检查 product_barcode 表是否包含条形码字段
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-06
    • 2015-09-27
    • 2020-09-28
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多