gpt4 book ai didi

angularjs - POSTing 到 REST Framework 时,Django 抛出列不能为空错误

转载 作者:行者123 更新时间:2023-12-02 21:05:17 24 4
gpt4 key购买 nike

Django REST Framework 正在报告一个值为空的错误,即使我在发布数据时发送该值也是如此。

Django 报告的错误是:

django.db.utils.IntegrityError: (1048, "Column 'owner_id' cannot be null")
[04/Apr/2016 18:40:58] "POST /api/items/ HTTP/1.1" 500 226814

POST 到 Django REST Framework API 的 Angular 2 代码是:

    let body = JSON.stringify({ url: 'fred', item_type: 'P', owner_id: 2 });

let headers = new Headers();
headers.append('Content-Type', 'application/json');

this.http.post('http://127.0.0.1:8000/api/items/',
body, {
headers: headers
})
.subscribe(
data => {
alert(JSON.stringify(data));
},
err => alert('POST ERROR: '+err.json().message),
() => alert('POST Complete')
);

我的 Django API View 如下所示:

class ItemViewSet(viewsets.ModelViewSet):
queryset = Item.objects.all().order_by('-date_added')
serializer_class = ItemSerializer

"""
Use the API call query params to determing what to return

API params can be:

?user=<users_id>&num=<num_of_items_to_return>&from=<user_id_of_items_to_show>
"""

def get_queryset(self):
this_user = self.request.query_params.get('user', None)
restrict_to_items_from_user_id = self.request.query_params.get('from', None)
quantity = self.request.query_params.get('num', 20)

if restrict_to_items_from_user_id is not None:
queryset = Item.objects.filter(owner=restrict_to_items_from_user_id, active=True).order_by('-date_added')[0:int(quantity)]
elif this_user is not None:
queryset = Item.objects.filter(active=True, credits_left__gt=0).exclude(pk__in=Seen.objects.filter(user_id=this_user).values_list('item_id', flat=True))[0:int(quantity)]
else:
queryset = Item.objects.filter(active=True, credits_left__gt=0)[0:int(quantity)]

print("User id param is %s and quantity is %s" % (user_id,quantity))

return queryset

相关模型是:

class Item(models.Model):

ITEM_TYPES = (
('V', 'Vine'),
('Y', 'YouTube'),
('P', 'Photo'), # Photo is stored by us on a CDN somewhere
('F', 'Flickr'),
('I', 'Instagram'),
('D', 'DeviantArt'),
('5', '500px'),
)
owner = models.ForeignKey(User, on_delete=models.CASCADE) # Id of user who owns the item
title = models.CharField(max_length=60, default='') # URL of where item resides (e.g. Vine or YouTube url)
url = models.CharField(max_length=250, default='') # URL of where item resides (e.g. Vine or YouTube url)
item_type = models.CharField(max_length=1, choices=ITEM_TYPES) # Type of item (e.g. Vine|YoutTube|Instagram|etc.)
keywords = models.ManyToManyField(Keyword, related_name='keywords')
# E.g. Art, Travel, Food, etc.
credits_applied = models.IntegerField(default=10, help_text='Total number of credits applied to this item including any given by VeeU admin')
# Records the total number of credits applied to the Item
credits_left = models.IntegerField(default=10, help_text='The number of credits still remaining to show the item')
# Number of credits left (goes down each time item is viewed
credits_gifted = models.IntegerField(default=0, help_text='The number of credits this item has been gifted by other users')
# Number of credits users have gifted to this item
date_added = models.DateTimeField(auto_now_add=True) # When item was added
liked = models.IntegerField(default=0) # Number of times this item has been liked
disliked = models.IntegerField(default=0) # Number of times this item has been disliked
active = models.BooleanField(default=True, help_text='If you mark this item inactive please say why in the comment field. E.g. "Inapproriate content"')
# True if item is available for showing
comment = models.CharField(max_length=100, blank=True) # Comment to be applied if item is inactive to say why

# Add defs here for model related functions

# This to allow url to be a clickable link
def item_url(self):
return u'<a href="%s">%s</a>' % (self.url, self.url)
item_url.allow_tags = True

def __str__(self):
return '%s: Title: %s, URL: %s' % (self.owner, self.title, self.url)

我看不出我的 POST 调用或 Django 代码有什么问题。

编辑:添加序列化器代码这是关联的序列化器

class ItemSerializer(serializers.HyperlinkedModelSerializer):
username = serializers.SerializerMethodField()

def get_username(self, obj):
value = str(obj.owner)
return value

def get_keywords(self, obj):
value = str(obj.keywords)
return value

class Meta:
model = Item
fields = ('url', 'item_type', 'title', 'credits_applied', 'credits_left', 'credits_gifted', 'username', 'liked', 'disliked')

最佳答案

您的序列化程序没有所有者字段,并且您的 View 也没有提供所有者字段。由于它在您的模型中不为空,因此数据库会提示这一点。

您应该覆盖 View 的 perform_update并添加the owner as extra argument to the serializer

关于angularjs - POSTing 到 REST Framework 时,Django 抛出列不能为空错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36408441/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com