2

我有一个带有GenericForeignKey. 调用cache.set(key, trac_obj)时,失败。我想知道GenericForeignKey是不是罪魁祸首?

# models.py
class Trac(models.Model):

    user = models.ForeignKey(User, related_name="%(class)s", null=False)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        unique_together = (('user', 'content_type', 'object_id'),)

# views.py
obj = SomeUserProfile # Django UserProfile (or any other model object)
content_type = ContentType.objects.get_for_model(type(obj))
trac_obj = Trac(user=request.user, content_type=content_type, object_id=obj.pk,
                                   content_object=obj)
trac_obj.save()
cache_key = 'Trac-{0}-{1}-{2}'.format(user.id, content_type.id, obj.id)
cache.set(cache_key, trac_obj)

这是错误消息:

File ".../python2.7/site-packages/memcache.py", line 751, in _val_to_store_info
pickler.dump(val)
File "/usr/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
4

1 回答 1

1

该错误似乎是因为无法直接腌制该.save()方法的结果。在保存对象之前尝试设置缓存。

如果你必须腌制.save(),似乎有一些方法在这个OP的答案中详细说明:http: //bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods

于 2015-06-18T12:37:19.633 回答