如何在Django Rest中发布对象时更新一些数据?

时间:2016-09-01 15:07:03

标签: django django-rest-framework

我有这个序列化器:

class LikeSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(queryset=ExtUser.objects.all(), required=False, allow_null=True, default=None)
    class Meta:
        model = Like
        field = ('user', 'post')


    def create(self, validated_data):

        post = Post(id=validated_data['post'], author=validated_data['user'])
        #post=Post.objects.get(pk=validated_data['post'])
        post.rating += 1
        print(post)
        post.save()
        return Like.objects.create(**validated_data)

当我尝试保存Like对象TypeError: int() argument must be a string or a number, not 'Post'

时,我收到错误

尝试添加int(),但它没有帮助,我想我不正确更新Post对象

Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Library/Python/2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Python/2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "/Library/Python/2.7/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/rest_framework/decorators.py", line 53, in handler
    return func(*args, **kwargs)
  File "/Users/olegklimakov/Documents/6rp/likes/views.py", line 19, in send_like
    serializer.save(user=request.user, isLiked=True)
  File "/Library/Python/2.7/site-packages/rest_framework/serializers.py", line 191, in save
    self.instance = self.create(validated_data)
  File "/Users/olegklimakov/Documents/6rp/likes/serializers.py", line 39, in create
    post.save()
  File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 700, in save
    force_update=force_update, update_fields=update_fields)
  File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 728, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 793, in _save_table
    forced_update)
  File "/Library/Python/2.7/site-packages/django/db/models/base.py", line 823, in _do_update
    filtered = base_qs.filter(pk=pk_val)
  File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 790, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 808, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1243, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1269, in _add_q
    allow_joins=allow_joins, split_subq=split_subq,
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1203, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "/Library/Python/2.7/site-packages/django/db/models/sql/query.py", line 1099, in build_lookup
    return final_lookup(lhs, rhs)
  File "/Library/Python/2.7/site-packages/django/db/models/lookups.py", line 19, in __init__
    self.rhs = self.get_prep_lookup()
  File "/Library/Python/2.7/site-packages/django/db/models/lookups.py", line 57, in get_prep_lookup
    return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 744, in get_prep_lookup
    return self.get_prep_value(value)
  File "/Library/Python/2.7/site-packages/django/db/models/fields/__init__.py", line 976, in get_prep_value
    return int(value)
TypeError: int() argument must be a string or a number, not 'Post'

发布模型:

class Post(models.Model):
    id = models.AutoField(primary_key=True)
    date_create = models.DateField(auto_now_add=True)
    date_change = models.DateField(auto_now=True)

    title = models.CharField(max_length=250)  # Max Length of title = 250
    description = models.CharField(max_length=1000)  # Max Length = 1000 chars
    rating = models.IntegerField(default=1)
    author = models.ForeignKey('extuser.ExtUser', blank=True, null=True)

    def __unicode__(self):
        return u"%s" % self.id

2 个答案:

答案 0 :(得分:0)

似乎在声明中

  

“发布(id = validated_data ['post'], author = validated_data ['user'])”,

validated_data ['post']为您提供发布对象,而不是 int 对象, 但是Post模型中的'id'需要一个int对象。

这可能是你得到错误的原因。

答案 1 :(得分:0)

@transactional
def create(self, validated_data):
    post = Post(id=validated_data['post'], author=validated_data['user'])
    post.rating += 1
    post.save()
    return super(self, LikeSerializer).create(validated_data)

让ModelSerializer创建它的工作很好,还要注意你肯定想使用事务来保持数据的一致性

此外,下面的代码创建了新的Post实体:

post = Post(...)
post.save()

你肯定需要获得现有的Post实体 Post.objects.filter(...).first()