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