无法分配“u”“”:“Company.parent”必须是“公司”例 [英] Cannot assign "u''": "Company.parent" must be a "Company" instance

查看:113
本文介绍了无法分配“u”“”:“Company.parent”必须是“公司”例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



无法分配u:Company.parent必须是公司实例。
我不知道还有什么要做的。
视图代码仍然是半烤,对不起。
我是否将错误的参数传递给表单?



我有以下模型:





  class Company(AL_Node):
parent = models.ForeignKey('self',
related_name ='children_set',
null = True,
db_index = True)
node_order_by = ['id','company_name']
id = models.AutoField(primary_key = True )
company_name = models.CharField(max_length = 100L,db_column ='company_name')#字段名称小写。
next_billing_date = models.DateTimeField()
last_billing_date = models.DateTimeField(null = True)
weekly ='we'
two_a_month ='2m'
every_two_weeks =' 2w'
monthly ='mo'
billing_period_choices =(
(weekly,'Weekly'),
(every_two_weeks,'每两周'),
(two_a_month ,每两周),
(每月,每月),

billing_period = models.CharField(max_length = 2,
choices = billing_period_choices,
default = weekly)

objects = CompanyManager()

以下表单.py:

  class newCompany(ModelForm):
company_name = forms.CharField(label ='Company Name'
widget = forms.TextInput(attrs = {'class':'oversize expand input-text'}))
billing_period = forms.ModelChoiceFie ld
next_billing_date = forms.CharField(widget = forms.TextInput(attrs = {'class':'input-text small','id':'datepicker'}))
parent = forms.CharField (widget = forms.HiddenInput(),required = False)

class Meta:
model = Company
fields = [company_name,parent,billing_period next_billing_date]

以下视图:

  def create_company(request):
userid = User.objects.get(username = request.user).id
my_company_id = CompanyUsers.objects.get(user_id = userid).company_id
my_company_name = Company.objects.get(id = my_company_id).company_name
machines = Title.objects.raw(
'select machines.id,title.name,machines (.moneyin,machines.moneyout,moneyin-moneyout as profit,machines.lastmoneyinoutupdate)(从auth_user中选择auth_user.username,其中machines.operator = auth_user.id)作为运算符,(从auth_user选择auth_user.username,其中machi nes.readers = auth_user.id)作为读取器从机器,标题在哪里machines.title = title.id和machines.company_id =%s',
[my_company_id])
如果request.method ==' POST':
form_company = newCompany(request.POST)
如果form_company.is_valid():
new_company = form_company.save(commit = False)
new_company.parent = my_company_id
如果request.POST.get('select_machine'):
selected_machine = request.POST.getlist('select_machine')
percent = request.POST.get('percentage')
如果不是Beneficiary.objects.check_assign_machine(my_company_id,selected_machine,percentage):
target_company_name = new_company.company_name
target_company_id = Company.objects.get(company_name = target_company_name).id
new_company.save ()
Machines.objects.assign_machine(target_company_id,selected_machine)
Beneficiary.objects.create_benef iciary(percent,target_company_name,my_company_id,selected_machine)
else:
invalid_machines = Beneficiary.objects.check_assign_machine(my_company_id,selected_machine,percentage)
return render(request,'lhmes / createcompany.html' ,
{'form_company':form_company,'machines':machines,'my_company_name':my_company_name,'invalid_machines':invalid_machines})
else:
new_company.save()

else:
form_company = newCompany()

return render(request,'lhmes / createcompany.html',
{'form_company':form_company,'machines' :机器'my_company_name':my_company_name})


解决方案

错误消息表示您正在尝试与字符串建立关系,但Django希望该值成为公司模型的一个实例。您应该为外键字段分配一个真正的模型实例,而不是仅将主键分配。



我在代码中发现了几个分配PK的地方:

  new_company.parent = my_company_id 

模型希望它是一个实例:

  new_company.parent = Company.objects .get(id = my_company_id)

我真的不记得如果这样, :

  new_company.parent_id = int(my_company_id)

这将免去数据库的旅行。


I am getting this at every attempt.

Cannot assign "u''": "Company.parent" must be a "Company" instance. I do not know what else to do. The view code is still half baked, sorry for that. Am I passing wrong parameters to the form?

I have the following model:

models.py

class Company(AL_Node):
  parent = models.ForeignKey('self',
                             related_name='children_set',
                             null=True,
                             db_index=True)
  node_order_by = ['id', 'company_name']
  id = models.AutoField(primary_key=True)
  company_name = models.CharField(max_length=100L, db_column='company_name') # Field name made lowercase.
  next_billing_date = models.DateTimeField()
  last_billing_date = models.DateTimeField(null=True)
  weekly = 'we'
  twice_a_month = '2m'
  every_two_weeks = '2w'
  monthly = 'mo'
  billing_period_choices = (
    (weekly, 'Weekly'),
    (every_two_weeks, 'Every two weeks'),
    (twice_a_month, 'Every two weeks'),
    (monthly, 'Monthly'),
  )
  billing_period = models.CharField(max_length=2,
                                    choices=billing_period_choices,
                                    default=weekly)

  objects = CompanyManager()

The following forms.py:

class newCompany(ModelForm):
  company_name = forms.CharField(label='Company Name',
                                widget=forms.TextInput(attrs={'class': 'oversize expand input-text'}))
  billing_period = forms.ModelChoiceField
  next_billing_date = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-text small', 'id': 'datepicker'}))
  parent = forms.CharField(widget=forms.HiddenInput(), required=False)

  class Meta:
    model = Company
    fields = ["company_name", "parent", "billing_period", "next_billing_date"]

The following view:

def create_company(request):
  userid = User.objects.get(username=request.user).id
  my_company_id = CompanyUsers.objects.get(user_id=userid).company_id
  my_company_name = Company.objects.get(id=my_company_id).company_name
  machines = Title.objects.raw(
    'select machines.id, title.name, machines.moneyin, machines.moneyout, moneyin - moneyout as profit, machines.lastmoneyinoutupdate, (select auth_user.username from auth_user where machines.operator = auth_user.id) as operator, (select auth_user.username from auth_user where machines.readers = auth_user.id) as readers from machines, title where machines.title = title.id and machines.company_id =%s',
    [my_company_id])
  if request.method == 'POST':
    form_company = newCompany(request.POST)
    if form_company.is_valid():
      new_company = form_company.save(commit=False)
      new_company.parent = my_company_id
      if request.POST.get('select_machine'):
        selected_machine = request.POST.getlist('select_machine')
        percentage = request.POST.get('percentage')
        if not Beneficiary.objects.check_assign_machine(my_company_id, selected_machine, percentage):
           target_company_name = new_company.company_name
           target_company_id = Company.objects.get(company_name=target_company_name).id
           new_company.save()
           Machines.objects.assign_machine(target_company_id, selected_machine)
           Beneficiary.objects.create_beneficiary(percentage, target_company_name, my_company_id, selected_machine)
        else:
          invalid_machines = Beneficiary.objects.check_assign_machine(my_company_id, selected_machine, percentage)
          return render(request, 'lhmes/createcompany.html',
                {'form_company': form_company, 'machines': machines, 'my_company_name': my_company_name, 'invalid_machines' : invalid_machines})
      else:
        new_company.save()

  else:
    form_company = newCompany()

  return render(request, 'lhmes/createcompany.html',
                {'form_company': form_company, 'machines': machines, 'my_company_name': my_company_name})

解决方案

The error message says you are trying to set a relationship with a string but Django expects the value to be an instance of the Company model. You should assign the foreign key fields with a real model instance instead of only the primary key.

I've spotted a few places in the code where you are assigning a PK:

new_company.parent = my_company_id

Where the model expects it to be an instance:

new_company.parent = Company.objects.get(id=my_company_id)

I really don't remember if this works, but you can try:

new_company.parent_id = int(my_company_id)

This would spare a trip to the database.

这篇关于无法分配“u”“”:“Company.parent”必须是“公司”例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆