Django'NonType'对象不可迭代

时间:2016-03-03 23:51:24

标签: django forms choice

我收到以下错误

'/ blocks / choices /的TypeError NoneType'对象不可迭代

我做错了什么?

查看

def choices(request):

    form = RoomLogChoices()
    form.fields['choice'].choices = list()
    for i in Room.objects.all():
        form.fields['choice'].choices = form.fields['choice'].choices.append(
            (
                i.room_name,
                list(
                    (o.id, o.room_value) for o in RoomLog.objects.filter(room=i).order_by('room')
                )
            )
        )

形式

class RoomLogChoices(forms.ModelForm):
    choice = forms.ModelChoiceField(
        queryset=RoomLog.objects.all().order_by('room__room_name', 'room_value')
    )

    class Meta:
        model = RoomLog
        fields = '__all__'

编辑: 以下是我要求的模型。我出于以下原因使用两种型号:Room和RoomLog。 RoomLog仅用于跟踪房间值更新的历史记录。

模型

class Room(models.Model):
    room_name = models.CharField(max_length= 10)
    room_value = models.PositiveSmallIntegerField(default=0)
    flat = models.ForeignKey(Flat)
    created_date = models.DateField(auto_now_add= True)
    created_time = models.TimeField(auto_now_add= True)

    def __init__(self, *args, **kwargs):
        super(Room, self).__init__(*args, **kwargs)
        self.value_original = self.room_value


    def save(self, **kwargs):
        with transaction.atomic():
            response = super(Room, self).save(**kwargs)
            if self.value_original != self.room_value:
                room_log = RoomLog()
                room_log.room = self
                room_log.room_value = self.value_original
                room_log.save()

            return response

    class Meta:
        ordering = ('room_name',)

    def __unicode__(self):
        return self.room_name


class RoomLog(models.Model):
    room = models.ForeignKey(Room)
    room_value = models.PositiveSmallIntegerField(default=0)
    update_date = models.DateField(auto_now_add= True)
    update_time = models.TimeField(auto_now_add= True)

    def __str__(self):
        return '%s | %s | %s' % (self.room, self.update_date, self.update_time)

1 个答案:

答案 0 :(得分:1)

list.append更新列表"到位"并返回无

例如:

my_list = [1, 2, 3]
new_list = my_list.append(4)
print my_list, new_list
  

[1,2,3,4]无

只需删除赋值语句。

def choices(request):

form = RoomLogChoices()
form.fields['choice'].choices = list()
for i in Room.objects.all():
    form.fields['choice'].choices.append(
        (
            i.room_name,
            list(
                (o.id, o.room_value) for o in RoomLog.objects.filter(room=i).order_by('room')
            )
        )
    )