无法分配“[u'192.168.99.1',u'192.168.99.1']”:“MultiWAN.nameserver”必须是“NameServer”实例

时间:2012-05-25 11:44:46

标签: python django django-models foreign-keys

考虑以下django模型

class MultiWAN(models.Model):

    isp_name = models.CharField(max_length=10)
    description  = models.TextField(null=True)
    ip_address   = models.IPAddressField(null=True)
    subnet       = models.IPAddressField(null=True)
    gateway      = models.IPAddressField(null=True)
    nameserver   = models.ForeignKey('NameServer')
    weight       = models.IntegerField(null=False)
    interface    = models.CharField(max_length=5) 



class NameServer(models.Model):
    """  A Isp can have more than one nameserver so far we are declearing a seperate table 
    """         
    name = models.IPAddressField(null=False)    

我写了一个相应的视图来接受用户输入并保存到db

def multiwan_info_save(request):

  #  try:
        isp_nm = request.POST['ispname_mw']
        desc_mw  = request.POST['desc_mw']
        ip_address_mw  = request.POST['ip_address_mw']
        subnet_mw = request.POST['subnet_mw']
        nameserver_mw = request.POST.getlist('nameserver_mw')
       # nameserver2_mw = request.POST['nameserver2_mw']
        gateway_mw = request.POST['gateway_mw']
        weight_mw = request.POST['weight_mw']
        interface_mw = request.POST['interface_mw']
        print "+++++++++++++++================="
        print nameserver_mw
        nmservr = NameServer()
        mv = MultiWAN(isp_name=isp_nm,description=desc_mw,ip_address=ip_address_mw,subnet = subnet_mw,gateway=gateway_mw,weight=weight_mw,interface = interface_mw,nameserver = nameserver_mw)

        mv.save()
    #except:

虽然我想保存但是我收到了上述错误。请帮助我,我错了。

2 个答案:

答案 0 :(得分:2)

您在NameServer模型上将MultiWAN.nameserver定义为外键,因此您需要将单个NameServer实例传递给MultiWAN,即:

nameserver = NameServer.objects.create(name="XXX.XXX.XXX.XXX")
mv = MultiWan.objects.create(nameserver=nameserver, ....)

现在假设你传递了一个IP地址列表,我猜你的MultiWAN / NameServer关系错了 - 看起来你希望NameServer在MultiWAN上有一个外键。

作为旁注:您应该使用Form(或ModelForm),因为它会清理大部分输入并进行验证。

答案 1 :(得分:0)

正如bruno所说,您必须传递NameServer对象,因为您将字段声明为ForeignKeys,但也考虑在NameServer存在之前进行检查。一个好的做法是使用objects.get_or_create而不是create。

nameserver, is_new = NameServer.objects.get_or_create(name='...')

这样您就会收到名称服务器实例,而is_new将为True或False,具体取决于对象是否已创建。