在django模型中创建条目时获得奇怪的ValueError

时间:2017-05-02 17:14:48

标签: python django python-3.x django-models

我正在Django模型中创建一个条目,但它显示的ValueError对于一个甚至不存在的字段

我在manage.py shell中使用外部脚本

python3 manage.py shell

>>> exec(open('file_name.py').read())

file_name.py(忽略名称:D)

from jtc.models import *

m = Movies.objects.get(title__icontains = "Badrinath")
mul = Multiplex.objects.get(movie__icontains = 'Badrinath', name = "PVR")
date = mul.date.all()
time = mul.time.all()
seat = Snumber.objects.filter(seat_avail = True)

st = Snumber.objects.get(seat_avail = True, seat_name = 'A1')
dt = Date.objects.get(date = '2017-05-10')
tm = Time.objects.get(timing='09:00:00')

Seats.objects.bulk_create(
    [
        Seats(movie_name = m, multiplex_name = mul,
              seat_no = st, date = dt, time=tm ),
    ]
)

这是我得到的错误

    Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<string>", line 23, in <module>
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/base.py", line 550, in __init__
    setattr(self, prop, kwargs[prop])
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 499, in __set__
    manager = self.__get__(instance)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
    return self.related_manager_cls(instance)
  File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 783, in __init__
    (instance, self.source_field_name))
ValueError: "<Seats: PVR Dehradun Badrinath ki dulhaniya 2017-05-10 09:00:00>" needs to have a value for field "seats" before this many-to-many relationship can be used.

这是我的座位模特

class Seats(models.Model):
    seat_no = models.ManyToManyField(Snumber)
    movie_name = models.ForeignKey(Movies)
    multiplex_name = models.ForeignKey(Multiplex)
    date = models.ForeignKey(Date)
    time = models.ForeignKey(Time)

    def __str__(self):
        b = str(self.date)
        c = str(self.time)
        d = str(self.multiplex_name)
        return d+" "+b+" "+c

2 个答案:

答案 0 :(得分:1)

在这种情况下,错误消息并非非常有用。它试图说的是,除非你拥有两个对象的id,否则你不能保存ManyToMany关系。您需要先保存Seats的实例,然后添加ManyToMany字段:

seats = Seats.objects.create(movie_name=m, multiplex_name=mul, 
    date=dt, time=tm)
seats.seat_no.add(st)

您可以在docs中了解更多相关信息。

答案 1 :(得分:0)

在这一行

Seats.objects.bulk_create(
    [
        Seats(movie_name = m, multiplex_name = mul,
              seat_no = st, date = dt, time=tm, seats = 1 ),
    ]
)

您正在设置seats = 1。但Seats模型没有seats字段。这很可能是您收到错误的原因。