无法使用API​​将数字列表保存到模型

时间:2019-07-13 12:11:41

标签: python django

im试图使用shell创建一个从1到9的列表,以便用户选择他可以预订的票数

外壳:

>>> Passenger = list(range(1,10))
>>> Passenger.save()
Traceback (most recent call last):
>  File "<console>", line 1, in <module>
> AttributeError: 'list' object has no attribute 'save'

Models.py:

class Ticket(models.Model):
    GENDER = (
        ('m', 'Male'),
        ('f', 'Female'),
    )

    trip = models.ForeignKey(Trip, related_name="tickets", null=True, on_delete=models.CASCADE)
    booking_time = models.DateTimeField(auto_now_add=True, blank=True)
    first_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False)
    middle_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False)
    last_name = models.CharField(validators=[validate_string], null=True, max_length=100, blank=False)
    email = models.EmailField(max_length=70,blank=True, null= True)
    gender = models.CharField(max_length=1, choices=GENDER)

    def __str__(self):
        return "{}".format(self.first_name)

Views.py:

def trips_page(request, trip_id):
    trip = get_object_or_404( Trip,pk=trip_id)
    error = None
    ticket = None
    if request.method == 'POST':
        first_name = request.POST.get('first_name')
        middle_name = request.POST.get('middle_name')
        last_name = request.POST.get('last_name')
        email = request.POST.get('email')
        gender = request.POST.get('gender')
        ticket = Ticket(trip=trip,first_name=first_name, middle_name=middle_name,
            last_name=last_name, email=email,gender=gender)
        try:
            ticket.full_clean()
            ticket.save()
            return redirect('tickets',ticket_id=ticket.id)
        except ValidationError as e:
            error = dict(e)
            print(e)
    context = {'trip' : trip, 'error':error, 'ticket':ticket }
    return render(request, 'details/trips.html', context)

1 个答案:

答案 0 :(得分:0)

list(range(1,10))只是数字列表。

为了能够保存模型对象,您需要创建一个对象:

for i in range(1, 10):
    Passenger.objects.create(pk=i)