ValueError:无法在 django 中分配

发布于 2024-12-18 15:37:35 字数 3799 浏览 1 评论 0原文

当我尝试向模型添加/发布数据时遇到问题。 这就是我在 python manage.py shell 中所做的:

>>> from booking.models import *
>>> qa = Product.objects.get(id=5)
>>> sd = Booking.objects.create(
... date_select = '2011-11-29',
... product_name = qa.name,
... quantity = 1,
... price = qa.price,
... totalcost = 20,
... first_name = 'lalala',
... last_name = 'sadsd',
... contact = '2321321',
... product = qa.id)
Traceback (most recent call last):
  File "<console>", line 10, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 138, in create
    return self.get_query_set().create(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 358, in create
    obj = self.model(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 352, in __init__
    setattr(self, field.name, rel_obj)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 331, in __set__
    self.field.name, self.field.rel.to._meta.object_name))
ValueError: Cannot assign "5": "Booking.product" must be a "Product" instance.

我不知道为什么会发生这种情况...... product = qa.id 不等于 Booking.product?

这是我的 model.py

from django.db import models

# Create your models here.
class Product(models.Model):
    name = models.CharField(max_length=50, null=True, unique=False)
    quantity = models.IntegerField(max_length=10, null=True)
    price = models.FloatField()
    def __unicode__(self):
        return self.name

class Booking(models.Model):
    date_select = models.DateField(auto_now=False, auto_now_add=False)
    product_name = models.CharField(max_length=50, blank=True, null=True)
    quantity = models.IntegerField(max_length=10, blank=True, null=True)
    price = models.FloatField()
    totalcost = models.FloatField()
    first_name = models.CharField(max_length=50, null=True, blank=True, unique=False)
    last_name = models.CharField(max_length=50, null=True, blank=True, unique=False)
    contact = models.CharField(max_length=50, null=True, blank=True, unique=False)
    product = models.ForeignKey(Product)
    def __unicode__(self):
        return self.first_name

和 handlers.py

from django.utils.xmlutils import SimplerXMLGenerator
from piston.handler import BaseHandler
from booking.models import *
from piston.utils import rc, require_mime, require_extended, validate
class BookingHandler(BaseHandler):
    allowed_method = ('GET', 'POST', 'PUT', 'DELETE')
    fields = ('id', 'date_select', 'product_name', 'quantity', 'price','totalcost', 'first_name', 'last_name', 'contact', 'product')
    model = Booking

    def read(self, request, id):
        if not self.has_model():
            return rc.NOT_IMPLEMENTED
        try:
            inst = self.model.objects.get(id=id)
            return inst
        except self.model.MultipleObjectsReturned:
            return rc.DUPLICATE_ENTRY
        except self.model.DoesNotExist:
            return rc.NOT_HERE

    def create(self, request, *args, **kwargs):
        if not self.has_model():
            return rc.NOT_IMPLEMENTED

        attrs = self.flatten_dict(request.POST)
        if attrs.has_key('data'):
            ext_posted_data = SimplerXMLGenerator(request.POST.get('data'))
            attrs = self.flatten_dict(ext_posted_data)
        try:
            inst = self.model.objects.get(**attrs)
            return rc.DUPLICATE_ENTRY
        except self.model.DoesNotExist:
            inst = self.model(**attrs)#error??
            inst.save()
            return inst
        except self.model.MultipleObjectsReturned:
            return rc.DUPLICATE_ENTR

有谁可以帮助我了解我的情况吗?

提前致谢...

I have encountered a problem when I was trying to add/post a data to my models.
this is what i have done in my python manage.py shell:

>>> from booking.models import *
>>> qa = Product.objects.get(id=5)
>>> sd = Booking.objects.create(
... date_select = '2011-11-29',
... product_name = qa.name,
... quantity = 1,
... price = qa.price,
... totalcost = 20,
... first_name = 'lalala',
... last_name = 'sadsd',
... contact = '2321321',
... product = qa.id)
Traceback (most recent call last):
  File "<console>", line 10, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 138, in create
    return self.get_query_set().create(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 358, in create
    obj = self.model(**kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py", line 352, in __init__
    setattr(self, field.name, rel_obj)
  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/related.py", line 331, in __set__
    self.field.name, self.field.rel.to._meta.object_name))
ValueError: Cannot assign "5": "Booking.product" must be a "Product" instance.

i don't have any idea why is that happening...
it is product = qa.id not equal to the Booking.product?

here is my model.py

from django.db import models

# Create your models here.
class Product(models.Model):
    name = models.CharField(max_length=50, null=True, unique=False)
    quantity = models.IntegerField(max_length=10, null=True)
    price = models.FloatField()
    def __unicode__(self):
        return self.name

class Booking(models.Model):
    date_select = models.DateField(auto_now=False, auto_now_add=False)
    product_name = models.CharField(max_length=50, blank=True, null=True)
    quantity = models.IntegerField(max_length=10, blank=True, null=True)
    price = models.FloatField()
    totalcost = models.FloatField()
    first_name = models.CharField(max_length=50, null=True, blank=True, unique=False)
    last_name = models.CharField(max_length=50, null=True, blank=True, unique=False)
    contact = models.CharField(max_length=50, null=True, blank=True, unique=False)
    product = models.ForeignKey(Product)
    def __unicode__(self):
        return self.first_name

and my handlers.py

from django.utils.xmlutils import SimplerXMLGenerator
from piston.handler import BaseHandler
from booking.models import *
from piston.utils import rc, require_mime, require_extended, validate
class BookingHandler(BaseHandler):
    allowed_method = ('GET', 'POST', 'PUT', 'DELETE')
    fields = ('id', 'date_select', 'product_name', 'quantity', 'price','totalcost', 'first_name', 'last_name', 'contact', 'product')
    model = Booking

    def read(self, request, id):
        if not self.has_model():
            return rc.NOT_IMPLEMENTED
        try:
            inst = self.model.objects.get(id=id)
            return inst
        except self.model.MultipleObjectsReturned:
            return rc.DUPLICATE_ENTRY
        except self.model.DoesNotExist:
            return rc.NOT_HERE

    def create(self, request, *args, **kwargs):
        if not self.has_model():
            return rc.NOT_IMPLEMENTED

        attrs = self.flatten_dict(request.POST)
        if attrs.has_key('data'):
            ext_posted_data = SimplerXMLGenerator(request.POST.get('data'))
            attrs = self.flatten_dict(ext_posted_data)
        try:
            inst = self.model.objects.get(**attrs)
            return rc.DUPLICATE_ENTRY
        except self.model.DoesNotExist:
            inst = self.model(**attrs)#error??
            inst.save()
            return inst
        except self.model.MultipleObjectsReturned:
            return rc.DUPLICATE_ENTR

does anyone can give me a hand about my situation?

thanks in advance...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阳光下的泡沫是彩色的 2024-12-25 15:37:36

您将产品指定为

product = qa.id

“While you should do”

product = qa

You assign the product as

product = qa.id

While you should do

product = qa
微凉 2024-12-25 15:37:36
product = qa

使用ForeingKey你应该分配一个对象,而不是id。

product = qa

Using ForeingKey you should assing an object, not id.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文