2017-04-05 42 views
0

類或模型Django的複雜查詢過濾器和創建列表

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,成本,標誌? 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"}] 

回答

0

1)你的杉木ST查詢將類似於下面的查詢

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) 
+0

給人異常類型的對象「product_barcode」有沒有屬性「條碼」 –

+0

支票product_barcode表包含條形碼字段 –

+0

是包含條形碼字段 –