返回引用Django模型

时间:2014-01-27 15:54:09

标签: django django-models

我有3个模特。

class ShipmentWeightMapping(models.Model):
    id = models.IntegerField(primary_key = True)
    weight = models.CharField(max_length = 255)
    status = models.CharField(max_length = 255)
    time = models.DateTimeField(auto_now = True, auto_now_add = True)
    shipment_id = models.ForeignKey('Shipment')



class ShipmentDimensionMapping(models.Model):
    id = models.IntegerField(primary_key = True)
    status = models.CharField(max_length = 255)
    time = models.DateTimeField(auto_now = True, auto_now_add = True)
    length = models.IntegerField()
    breadth = models.IntegerField()
    height = models.IntegerField()
    shipment_id = models.ForeignKey('Shipment')




class Shipment(models.Model):
    id = models.IntegerField(primary_key = True)
    job_id = models.CharField(max_length = 255)
    weights = models.ForeignKey('ShipmentWeightMapping')#backref
    dimensions = models.ForeignKey('ShipmentDimensionMapping')#backref
    time = models.DateTimeField(auto_now = True, auto_now_add = True, db_index = True)

我想将weightsdimensions反馈给各自的类,以便在查询id=1的货件模型时,我应该length,{{1}来自breadth的{​​{1}}和来自height的{​​{1}}而未分别查询ShipmentDimensionMappingweight

例如: - 目前我喜欢这个。

要获取ShipmentWeightMapping的货件明细,请执行以下操作。

ShipmentDimensionMapping

我是否有任何方法可以查询ShipmentWeightMapping并获取id = 1dimension_obj = ShipmentDimensionMapping.objects.filter(shipment_id = 1)[0] length = dimension_obj.length #similarly for other details in ShipmentDimensionMapping weight_obj = ShipmentWeightMapping.objects.filter(shipment_id = 1)[0] weight = weight_obj.weight #similarly for other details in ShipmentWeightMapping shipment_obj = Shipment.objects.filter(shipment_id = 1)[0] job_id = shipment_obj.job_id #similarly for other details in Shipment 的详细信息?

另外,我总是使用第0个索引shipment_obj的结果来获得结果。虽然返回的结果总是只包含1个项目,但仍需要ShipmentWeightMapping。我怎样才能避免这种情况?

1 个答案:

答案 0 :(得分:0)

由于权重和维度数据在其他表上,因此在不查询这两个表的情况下无法获取它们。

对于第二个问题,如果你知道只有一个条目,你可以这样做:

shipment_obj = Shipment.objects.get(id=1)

顺便说一句;您不必显式添加ID值,因为它们在您的代码中也被称为id,默认情况下是在Django中。