尝试加入Django中的OneToOne关系

时间:2017-02-23 19:56:58

标签: django django-queryset django-orm

我需要帮助使用Django进行连接,这看起来应该很容易。我查看了文档,但似乎不会因为某些原因加入。

我试图在我看来,模型.Photo和model.PhotoExtended一起加入,然后在视图中显示。目前我只是想获得model.Photo显示但有一个连接找到request.user并根据它过滤它。

他们在不同的应用程序中。

models.py for model.Photo

class Photo(ImageModel):
    title = models.CharField(_('title'),
                         max_length=60,
                         unique=True)
    slug = models.SlugField(_('slug'),
                        unique=True,
                        help_text=_('A "slug" is a unique URL-friendly title for an object.'))

models.py for model.PhotoExtended

class PhotoExtended(models.Model):

    Photo = models.OneToOneField(Photo, related_name='extended', help_text='Photo required', null=True)

    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, help_text='User that uploaded the photo')

views.py

class PhotoExtendedUserView(ListView):
    template_name = 'photo_user_list.html'

    def get_queryset(self):
        user = get_object_or_404(User, username=self.request.user)

        return Photo.objects.filter(photoextended__user=user)

1 个答案:

答案 0 :(得分:2)

您将related_name Photo设置为extended(因此不应该大写)class PhotoExtendedUserView(ListView): template_name = 'photo_user_list.html' def get_queryset(self): user = get_object_or_404(User, username=self.request.user) # 'extended' vs. 'photoextended' return Photo.objects.filter(extended__user=user) ,因此您需要按照以下方式进行过滤:

Error: Can't resolve all parameters for IconService: (?, ?)