user_id可能不是NULL

时间:2011-08-17 15:31:22

标签: django post django-models curl

我通过TastyPie为我的Django模型提供服务,在尝试发布新的预订模式时,我不断收到此错误:

error_message: "bookings_booking.user_id may not be NULL"

即使使用curl也会产生它:

curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"date": "2011-08-17", "time": "17:30", "duration": 30, "description": "meh", "user": "/api/v1/user/1/", "room": "/api/room/1/"}' http://localhost:8000/api/booking/

我已经尝试删除我的数据库并多次运行syncdb但问题仍然存在。

以下是我的Django模型:

class User(models.Model):
login       = models.CharField('login', max_length=12)
password    = models.CharField('password', max_length=12)
fullname    = models.CharField('fullname', max_length=30)

class Room(models.Model):
name        = models.CharField('room name', max_length=30)
code        = models.CharField('room code', max_length=4)

class Booking(models.Model):
date        = models.DateField('date booked')
time        = models.TimeField('time booked')
duration    = models.PositiveSmallIntegerField('duration booked') #x * 15
user        = models.ForeignKey(User, related_name='bookings')
room        = models.ForeignKey(Room, related_name='bookings')
description = models.TextField()

这是我的Tastypie资源:

class RoomResource(ModelResource):
class Meta:
    queryset = Room.objects.all()
    resource_name = 'room'

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'

class BookingResource(ModelResource):
    room = fields.ForeignKey(RoomResource, 'room')

    class Meta:
        queryset = Booking.objects.all()
        resource_name = 'booking'
        filtering = {
            "room"  :   ALL_WITH_RELATIONS,
            "date"  :   ['exact', 'range'],
            "time"  :   ['gte', 'lte']
        }
        authorization = Authorization()

1 个答案:

答案 0 :(得分:2)

我认为您需要将用户FK添加到BookingResource。像So ::

class BookingResource(ModelResource):
    room = fields.ForeignKey(RoomResource, 'room')
    user = fields.ForeignKey(UserREsource, 'user')

    class Meta:
        queryset = Booking.objects.all()
        resource_name = 'booking'
        filtering = {
            "room"  :   ALL_WITH_RELATIONS,
            "date"  :   ['exact', 'range'],
            "time"  :   ['gte', 'lte']
        }
        authorization = Authorization()