Django ValueError: Cannot assign must be an instance by models

Django ValueError: Cannot assign must be an instance by models

我有两个模型 Tax_settingsItem_Creation 我想使用 tax_id 来自 Tax_settings 作为 tax_codeItem_creation 中。我已经使用 tax_code 作为外键。现在我在 templates 中对其执行操作以获得 tax_code[=37= 的列表].但是得到这个错误

models.py

class Tax_Settings(models.Model):
    tax_id = models.IntegerField()
    name = models.CharField(max_length=50)
    tax_description = models.CharField(max_length=50)
    
    class Meta:
        verbose_name = "tax_id"
    def __str__(self):
        return self.tax_id
    
class Item_Creation(models.Model):
    item=models.CharField(max_length=50)
    hsn=models.IntegerField()
    item_code = models.IntegerField()
    item_description = models.CharField(max_length=50)
    unit = models.IntegerField()
    tax_code = models.ForeignKey(Tax_Settings,on_delete=models.CASCADE)

views.py

def item_creation(request):
    get_tax_code=Tax_Settings.objects.values_list('tax_id')[0]
    print(get_tax_code)
    
    if request.method == 'POST':
        item = request.POST['item']
        hsn = request.POST['hsn']
        item_code=request.POST['item_code']
        item_description=request.POST['item_description']
        unit=request.POST['unit']
        tax_code = request.POST['tax_code']
        
        item_details = Item_Creation.objects.create(item=item, hsn=hsn, item_code=item_code,item_description=item_description, unit=unit, tax_code=tax_code)
        item_details.save()
        print("item_details",item_details)
        return render(request,"settings/item-creation.html")
    return render(request,"settings/item-creation.html",{'get_tax':get_tax_code})

item-creation.html

<div class="col-md mb-2">
     <select  id="tax-code" class="form-control" name="tax_code" >
           <option value="">Select Tax Code</option>
                 {% if get_tax %}
                      {% for t in get_tax %}
                          <option value="{{t}}">{{t}}</option>
                      {% endfor %}
                {% endif %}
     </select>

这里的问题是您必须将 tax_id 作为您的主键,除非它将采用 'id'(这是自动创建的主键,因为您没有创建主键)。

将您的 tax_id 修改为 tax_id = models.IntegerField(primary_key=True) 并重新迁移

然后根据以下内容编辑您的观点

tax_code = request.POST['tax_code']
tax_obj = Tax_Settings.objects.get(tax_id=tax_code)
item_details = Item_Creation.objects.create(item=item, hsn=hsn, item_code=item_code,item_description=item_description, unit=unit, tax_code=tax_obj)
item_details.save()