Django - 多对一 - 无法分配必须是

时间:2017-01-19 03:01:14

标签: python django many-to-one

如果这是重复的帖子,我道歉。我花了几天时间研究并试图解决这个问题......但我已经走到了尽头。我有一个包含所有订单标题的模型(标题),我需要将它链接到它们来自的(MarketPlace模型)市场。 MarketPlace表中只有2或3行,但Header中的每一行都应与其中一行相关。

以下是我试图在shell中创建记录的方式:(我也可能这样做错了):

h = Header.objects.filter(retailOrderNum = '185680144')
a = Marketplace(id = None, contactName = 'MP Name',address1='555',address2='666',city = 'Salt Lake City'
 ,state = 'UT',zipCode='84104',country = 'US',phone='555-555-5555',channel=h)

我收到此错误:

无法指定“]>”:“MarketPlace.channel”必须是“标题”实例。

以下是我的模特:

class Header(models.Model):
    retailOrderNum = models.CharField(max_length=50,primary_key = True)
    orderNum = models.CharField(max_length=50)
    channel = models.CharField(max_length=50)
    orderDate = models.DateTimeField(null=True)
    contactName = models.CharField(max_length=500)
    address1 = models.CharField(max_length=1500)
    address2 = models.CharField(max_length=1500, null=True)
    city = models.CharField(max_length =100)
    state =models.CharField(max_length =100)
    zipCode =models.CharField(max_length=100,null=True)
    country = models.CharField(max_length =100)
    phone = models.CharField(max_length =100,null=True)
    #shippingSpecifications =models.CharField(max_length =100)
    shippingCode = models.CharField(max_length =100)
    orderShippedDate = models.DateTimeField(null=True)

    def __str__(self):
        return self.retailOrderNum


class Line(models.Model):
    retailOrderNum =models.ForeignKey(Header, on_delete=models.CASCADE,db_column='retailOrderNum')
    item = models.CharField(max_length =100)
    lineNo = models.IntegerField()
    lineId = models.CharField(max_length =100)
    itemId = models.CharField(max_length =100)
    qty = models.IntegerField()
    retail = models.FloatField()
    revenue = models.FloatField()
    shipping = models.FloatField()
    lineStatus = models.CharField(max_length =100)
    qtyShipped = models.IntegerField(default=0)
    trackingNumber = models.CharField(max_length =500,null=True)
    shipCarrier = models.CharField(max_length =100,null=True)
    shippedDate = models.DateTimeField(null=True)

    def __str__(self):
        return self.item



class MarketPlace(models.Model):
    channel = models.ForeignKey(Header)
    contactName = models.CharField(max_length=500)
    address1 = models.CharField(max_length=1500)
    address2 = models.CharField(max_length=1500, null=True)
    city = models.CharField(max_length =100)
    state =models.CharField(max_length =100)
    zipCode =models.CharField(max_length=100,null=True)
    country = models.CharField(max_length =100)
    phone = models.CharField(max_length =100,null=True)

1 个答案:

答案 0 :(得分:0)

以下代码返回一个查询集:

h = Header.objects.filter(retailOrderNum='185680144')

你需要只为通道参数提供一个模型(它在"MarketPlace.channel" must be a "Header" instance的追溯中表示 - 所以你应该使用它来代替;

h = Header.objects.get(retailOrderNum='185680144')