2016-05-16 68 views
1

我有3种型号 材料,计量单位,BIN_UOM'查询集' 对象有没有属性“ - Django的ORM问题

@with_author 
    class Material(models.Model): 
     version = IntegerVersionField() 
     code = models.CharField(max_length=30) 
     name = models.CharField(max_length=30) 
     slug = models.SlugField(max_length=80, blank=True) 
     description = models.TextField(null=True, blank=True) 
     materialuom = models.CharField(max_length=1, 
            choices=UOM_CHOICES) 
     creation_time = models.DateTimeField(auto_now_add=True, blank=True) 
     itemgroup = models.ForeignKey(ItemGroup, on_delete=models.PROTECT) 
     keywords = models.CharField(max_length=50,null=True, blank=True) 
     valid_from = models.DateTimeField(null=True, blank=True) 
     valid_to = models.DateTimeField(null=True, blank=True) 
     min_quantity = models.DecimalField(max_digits=19, decimal_places=10) 
     trigger_quantity = models.DecimalField(max_digits=19, decimal_places=10) 
     max_quantity = models.DecimalField(max_digits=19, decimal_places=10) 

    @with_author 
    class UOM(models.Model): 
     version = IntegerVersionField() 
     code = models.CharField(max_length=30) 
     name = models.CharField(max_length=30) 
     material = models.ForeignKey(Material) 
     description = models.TextField(null=True, blank=True) 



@with_author 
class UOM_BINUOM(models.Model): 
    version = IntegerVersionField() 
    UOM = models.ForeignKey(UOM) 
    BIN_UOM = models.ForeignKey(BIN_UOM) 
    quantityperunit = models.PositiveSmallIntegerField() 
    creation_time = models.DateTimeField(auto_now_add=True,blank=True) 

在输入我有我的材质ID

使用Django ORM我想获取我材质ID的UOM_BINUOM的所有对象。

在SQL:

Select * from UOM_BINUOM where UOM_BINUOM.uom in (Select uom from UOM where UOM.material = material) 

在ORM我想这样说:

uombinuom = UOM.objects.filter(material__in=material_id).uom_binuom_set.all().order_by('-id') 

或类似这样的

material = get_object_or_404(Material, pk=material_id) 
    uom = material.uom_set.all().order_by('-id') 
    uombinuom = uom.uom_binuom_set.all().order_by('-id') 

,但得到的错误

“查询集'物体没有属性ute'uom_binuom_set'

我在做什么错了,我该如何解决这个问题?

+0

'material_id'是一个id列表,还是一个id? – Alasdair

+0

material_id是单个标识 –

回答

1

uom_binuom_set是单个UOM实例

UOM.objects.get(pk=1).uom_binuom_set.all() 

但是,你有UOM_BINUOM.objects.filter(...),这是一个查询集。如错误所述,查询集没有uom_binuom_set方法。

您可以从UOM_BINUOM模型开始构建所需的查询集。

uombinuom = UOM_BINUOM.objects.filter(UOM__material=material_id) 

注意,因为material_id是一个ID,你并不需要使用__in

1

当你

uom = material.uom_set.all().order_by('-id') 

是这里的QuerySet。应在单个记录上调用uom_binuom_set而不是记录的QuerySet。 因此,您需要遍历 QuerySet并为每条记录调用.uom_binuom_set.all()

for record in uom: 
    uom_binuom = record.uom_binuom_set.all() 
    # do something with uom_binuom 

或者,如果你想与uom_binuom仅第一条记录,然后

uom_binuom = uom.first().uom_binuom_set.all() 
相关问题