django complex查询过滤器并创建列表

时间:2017-04-05 11:11:26

标签: mysql django python-2.7 django-models

类或模型

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_name,cost,flag ??使用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"}]

1 个答案:

答案 0 :(得分:0)

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 )