Django休息框架 - 无法序列化查询集

时间:2017-07-04 10:53:09

标签: django django-rest-framework

我尝试序列化查询集

def do(self):
        reservations = Reservation.objects.all()
        serializer = ReservationSerializer(data=reservations, many=True)
        if serializer.is_valid():
            encoded_data = json.dumps(serializer.data)
            r = requests.post('http://httpbin.org/post', headers={'Content-Type': 'application/json'}, data=encoded_data)
            print(r.text)
        else:
            print(serializer.errors)

我总是得到

的错误
  

{u'non_field_errors':[你需要一个项目清单,但得到的类型是“QuerySet”。']}

我尝试在查询集上使用values(),然后转换为list,但这样我就可以获得没有嵌套模型的对象

模型

class Reservation(models.Model):
    start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
    end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
    check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
    check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
    has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
    payed = models.BooleanField(verbose_name='Оплачено', default=False)
    reserved_days = models.ManyToManyField(Day, blank=False)
    additional_services = models.ManyToManyField(AdditionalService)
    guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
    reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)

class AdditionalService(models.Model):
    payment_date = models.CharField(verbose_name='Дата оплаты', max_length=200, blank=True)
    payment_type = models.CharField(verbose_name='Форма оплаты', max_length=200, blank=False)
    service = models.CharField(verbose_name='Услуга', max_length=200, blank=False)
    quantity = models.IntegerField(blank=False)
    price = models.FloatField(blank=False)

class Day(models.Model):
    date = models.DateField(auto_now=False, auto_now_add=False)
    price = models.FloatField()
    payment_method = models.CharField(max_length = 200, blank=True)
    payment_date = models.CharField(max_length=200, blank=True)
    room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)

class Room(models.Model):
    name = models.CharField(max_length = 200, null=True)
    id = models.AutoField(primary_key=True)
    room_id = models.CharField(max_length = 200, null=False)

    def __unicode__(self):
        return self.name

串行

class ReservationSerializer(serializers.ModelSerializer):
    reserved_days = DaySerializer(many=True)
    additional_services = AdditionalServicesSerializer(many=True)

    class Meta:
        model = Reservation
        fields = [
            'start',
            'end',
            'check_in_time',
            'check_out_time',
            'reserved_days',
            'additional_services',
            'has_refund',
            'payed',
            'guest_name',
            'reservation_number',
        ]

class DaySerializer(serializers.ModelSerializer):
    room = RoomSerializer()

    class Meta:
        model = Day
        fields = [
            'date',
            'price',
            'payment_method',
            'payment_date',
            'room',
        ]

class AdditionalServicesSerializer(serializers.ModelSerializer):
    class Meta:
        model = AdditionalService
        fields = [
            'payment_date',
            'payment_type',
            'service',
            'quantity',
            'price',
        ]

class RoomSerializer(serializers.ModelSerializer):
    class Meta:
        model = Room
        fields = [
            'room_id',
        ]

1 个答案:

答案 0 :(得分:9)

对于serialization,您不需要使用 -(void)StartAnmation { timer= [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(methodToAddImages) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; } - (void)methodsave { for (int i=0; i<5; i++) { UIImage *img=[self screenshotimageWithView:self.mainview]; [gifimages addObject:img]; } } 关键字,只需将queryset作为第一个位置参数传递:

- (UIImage ) screenshotimageWithView:(UIView )view
{

UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);

[view.layer renderInContext:UIGraphicsGetCurrentContext()];
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];

UIImage * img = UIGraphicsGetImageFromCurrentImageContext();

NSData *miths=UIImagePNGRepresentation(img);

UIImage *imge=[UIImage imageWithData:miths];

UIGraphicsEndImageContext();

return imge;
}