Django复杂的互依表查询

2024-09-30 22:16:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想计算由公司名称生成的条形码的数量

我试过一些代码

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'],其中company='公司名称'
  3. 批次代码,其中产品=['product1','product2','product3']

    • 产品1['bxyz'、'b2xyz'、'b3xyz']
    • 产品2['b1xyz','b4xyz','b3xyz']
    • 产品3['b9xyz'、'b6xyz'、'b3xyz']
  4. 计数批次代码['bxyz'、'b2xyz'、'b3xyz']['b1xyz'、'b4xyz'、'b3xyz']['b9xyz'、'b6xyz'、'b3xyz']的条形码。


Tags: nameselfaddfalsetrueauto产品models
1条回答
网友
1楼 · 发布于 2024-09-30 22:16:37

我希望,我很明白你想做什么,那么像这样的事情呢:

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

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

两个下划线用于连接表,就像在SQL中使用JOIN一样。基于PEP,您应该更改条形码类的名称(ProductBarcode)。为了将来,最好从它开始

相关问题 更多 >