无法访问对象

时间:2018-02-22 20:17:15

标签: python django python-2.7 django-models django-views

我整天都在处理一个问题而且我的智慧结束了。我有两个具有多种关系的模型(书签和boomark组)。我想在我的视图中访问与bookgroup相关的书签。当打印上下文达到高峰时,我得到None返回。我已经将以下代码粘贴在一个要点中...任何帮助都会非常感激。

models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import chain
import datetime
import hashlib

from django.db import models
from django.urls import reverse
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django_mysql.models import JSONField, Model
from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.utils import timezone
from django.conf import settings

class Bookmark(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks")
    bookmark_groups = models.ManyToManyField("BookmarkGroup")
    # meta
    created_at = models.DateTimeField(auto_now_add=True)
    modified_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('user', 'resource',)
        ordering = ('resource',)

    def __str__(self):
        return "{} | {}".format(self.user, self.resource)


class BookmarkGroup(models.Model):
    name = models.CharField(max_length=50)
    slug = models.SlugField(null=False, unique=True)
    bmark = models.ManyToManyField(Bookmark)
    def __str__(self):
        return self.name

views.py

from __future__ import unicode_literals
import json

from django.shortcuts import render, get_list_or_404
from django.http import JsonResponse
from django.views import View
from django.views.generic import DetailView

from app.serializers import BookmarkGroupSerializer
from app.models import Resource,Bookmark,ResourceShare,PrivateNote,BookmarkGroup
from app.views.resources import get_enriched_resources

class BookmarkGroupView(DetailView):
    model = BookmarkGroup
    def get_context_data(self, **kwargs):
        context = super(BookmarkGroupView, self).get_context_data(**kwargs)
        print(context['object'].bmark.resource)
        return context

1 个答案:

答案 0 :(得分:0)

这里的关键是ManyToMany关系,但你试图像一个对象一样访问它。

 context['object'].bmark.all()[0].resource

OR

context['object'].bmark.first().resource

<强>已更新: 空虚检查

try:
  resourse = context['object'].bmark.all()[0].resource
except:
  resourse = None

OR

bmarks = context['object'].bmark.all()
resourse = bmarks[0].resource if bmarks else None