【问题标题】:django complex query for interdependant tablesdjango对相互依赖表的复杂查询
【发布时间】:2017-03-29 20:12:36
【问题描述】:

Django 模型

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)

    def __unicode__(self):
        return self.product_name


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)

    def __unicode__(self):
        return self.batch


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)

    def __unicode__(self):
        return self.barcode

我想计算由 company_name 生成的条形码数量

我尝试了一些类似的代码

w=Product.objects.all().filter(company_name="company name")
print "w>>>",w
pid = []
for Pdata in w:
    pid.append(Pdata.id)
print "pid>>>",pid

在这里我找到属于特定公司的产品名称 ID,但之后我想找到属于产品 ID 的批次代码(在 ProductDetails),之后我需要计算所有属于批次代码的条形码。

简单来说

  1. 公司['公司名称']
  2. 产品 ['product1','product2','product3'] where company = '公司名称'
  3. 产品的批次代码 = ['product1','product2','product3']

    • product1 ['bxyz','b2xyz','b3xyz']
    • product2 ['b1xyz','b4xyz','b3xyz']
    • product3 ['b9xyz','b6xyz','b3xyz']
  4. count Barcodes where batch codes ['bxyz','b2xyz','b3xyz']['b1xyz','b4xyz','b3xyz']['b9xyz','b6xyz','b3xyz']

【问题讨论】:

    标签: python django list django-models


    【解决方案1】:

    我希望,我很了解你想要做什么,所以像这样的:

    count = product_barcode.objects.filter(batch__product__company_name='company name').count()
    

    这应该返回公司名称等于“公司名称”的所有产品的条形码数量。

    两个下划线用于连接表,就像在 SQL 中使用 JOIN。基于PEP,您应该更改条形码类的名称(ProductBarcode)。未来真的更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2011-10-26
      • 1970-01-01
      相关资源
      最近更新 更多