0

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

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'

谢谢!

4

1 回答 1

0

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

于 2015-02-24T10:26:34.027 回答