0

所以我有一个用户模型(由django提供的默认用户模型),一个Feed模型和一个评论模型。 Feed和评论都使用外键关系引用用户。我需要找到评论的Feed的用户,才能推送通知,但是我无法这样做,导致延迟加载。我试过prefetch_realtions,但是这只会导致用户模型中的所有用户。有没有办法在django中访问外键的主键? 的代码如下 - (models.py) -如何从django中的外键访问外键

class Feed(models.Model): 
    spot = models.ForeignKey(Spot, related_name='local_feeds') 
    title = models.CharField(max_length=100) 
    description= models.CharField(max_length=200) 
    pub_date = models.DateTimeField(auto_now_add=True) 
    feed_user = models.ForeignKey(settings.AUTH_USER_MODEL,  related_name='my_feeds') 
    flag = models.CharField(max_length=1) 


class Comment(models.Model): 
    feed = models.ForeignKey(Feed,related_name="comments") 
    comment = models.CharField(max_length=100) 
    pub_date = models.DateTimeField(default=datetime.now()) 
    comment_user = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='my_comments') 
    flag = models.CharField(max_length=1). 

我的序列化器类看起来是这样的 -

class FeedSerializer(serializers.HyperlinkedModelSerializer): 
    comments = serializers.HyperlinkedRelatedField(many=True, view_name='comment-detail',queryset=User.objects.all()) 
    class Meta: 
     model = Feed 
     fields = ('id','spot','title','description','feed_user', 'comments','flag','pub_date') 

class SpotSerializer(serializers.HyperlinkedModelSerializer): 

    local_feeds = FeedSerializer(required=False,many=True) 
    class Meta: 
     model = Spot 
     fields = ('id','name','position','local_feeds','address') 
     depth =4 


class CommentSerializer(serializers.HyperlinkedModelSerializer): 
    class Meta: 
     model= Comment 
     fields =('id','feed','comment','flag','pub_date','comment_user') 

,我一直在试图使用prefetch_related查询如下 -

feed_obj = Prefetch('my_feeds',queryset = Feed.objects.filter(id = instance.feed_id),to_attr = "curr_feed") 
user_obj= User.objects.all().prefetch_related(feed_obj) 

我回溯如下 -

ValueError at /Comment/ 
invalid literal for int() with base 10: 'asutoshkatyal' 
Request Method: POST 
Request URL: http://127.0.0.1:8000/Comment/ 
Django Version: 1.7 
Exception Type: ValueError 
Exception Value:  
invalid literal for int() with base 10: 'asutoshkatyal' 
Exception Location: /Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/fields/__init__.py in get_prep_value, line 915 
Python Executable: /Users/asutoshkatyal/.virtualenvs/fyshbowl/bin/python 
Python Version: 2.7.6 
Python Path:  
['/Users/asutoshkatyal/Desktop/cs242proj/fishbowl', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python27.zip', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/plat-darwin', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/plat-mac', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/plat-mac/lib-scriptpackages', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/Extras/lib/python', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/lib-tk', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/lib-old', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/lib-dynload', 
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7', 
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', 
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', 
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', 
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', 
'/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages'] 
Server time: Tue, 24 Feb 2015 11:34:06 +0000 

Environment: 


Request Method: POST 
Request URL: http://127.0.0.1:8000/Comment/ 

Django Version: 1.7 
Python Version: 2.7.6 
Installed Applications: 
('django.contrib.admin', 
'django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'geoposition', 
'geofeed', 
'rest_framework', 
'django.contrib.sites', 
'rest_framework.authtoken', 
'rest_auth', 
'zeropush', 
'debug_toolbar') 
Installed Middleware: 
(u'debug_toolbar.middleware.DebugToolbarMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.common.CommonMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware', 
'django.middleware.clickjacking.XFrameOptionsMiddleware') 


Traceback: 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 
    111.      response = wrapped_callback(request, *callback_args, **callback_kwargs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 
    57.   return view_func(*args, **kwargs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 
    85.    return self.dispatch(request, *args, **kwargs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 
    407.    response = self.handle_exception(exc) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 
    404.    response = handler(request, *args, **kwargs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/mixins.py" in create 
    21.   self.perform_create(serializer) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_create 
    26.   serializer.save() 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/serializers.py" in save 
    164.    self.instance = self.create(validated_data) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/rest_framework/serializers.py" in create 
    760.    instance = ModelClass.objects.create(**validated_data) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method 
    92.     return getattr(self.get_queryset(), name)(*args, **kwargs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/query.py" in create 
    372.   obj.save(force_insert=True, using=self.db) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/base.py" in save 
    590.      force_update=force_update, update_fields=update_fields) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/base.py" in save_base 
    627.         update_fields=update_fields, raw=raw, using=using) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/dispatch/dispatcher.py" in send 
    198.    response = receiver(signal=self, sender=sender, **named) 
File "/Users/asutoshkatyal/Desktop/cs242proj/fishbowl/geofeed/models.py" in push_notifications 
    71.  print(instance.feed.feed_user) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/fields/related.py" in __get__ 
    568.      qs = qs.filter(**params) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/query.py" in filter 
    691.   return self._filter_or_exclude(False, *args, **kwargs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude 
    709.    clone.query.add_q(Q(*args, **kwargs)) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q 
    1287.   clause, require_inner = self._add_q(where_part, self.used_aliases) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q 
    1314.      current_negated=current_negated, connector=connector) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter 
    1186.    condition = self.build_lookup(lookups, col, value) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_lookup 
    1094.      return final_lookup(lhs, rhs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/lookups.py" in __init__ 
    82.   self.rhs = self.get_prep_lookup() 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/lookups.py" in get_prep_lookup 
    85.   return self.lhs.output_field.get_prep_lookup(self.lookup_name, self.rhs) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup 
    646.    return self.get_prep_value(value) 
File "/Users/asutoshkatyal/.virtualenvs/fyshbowl/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value 
    915.   return int(value) 

Exception Type: ValueError at /Comment/ 
Exception Value: invalid literal for int() with base 10: 'asutoshkatyal' 

谢谢!

回答

0

这与延迟加载或prefetch_related无关。您可以通过执行my_comment.feed.feed_user直接从评论中获取订阅源用户。

+0

所以我使用“@receiver(post_save,sender = Comment) def push_notifications(sender,instance,** kwargs):”当有人发表评论时触发推送通知。当我使用instance.feed.feed_user时,我得到一个异常说 - “int()的无效字面量为10:” – 2015-02-24 11:18:41

+0

这不是足够的信息。请编辑您的问题以添加完整的回溯。 – 2015-02-24 11:21:48

+0

我已经包含了我的追踪。如果你需要其他东西,请告诉我。再次感谢! – 2015-02-24 11:31:18