通过多对多的关系正确地返回对象

时间:2013-08-19 06:32:06

标签: django django-models django-admin django-views

我的目标是显示属于我的用户名为' Admin'

的文章的可读列表

换句话说,给我所有Admin所拥有的文章。在我的示例数据中,我有Admin拥有1篇文章。

问题:当我返回对象时,它对此对象的表示完全不可读且无益。我想在这里为我的模型添加 unicode ()方法,但我不知道怎么做!

Model.py:

from django.db import models
from django.contrib.auth.models import User

class Article (models.Model):
    question = models.CharField(max_length=255, unique=True, blank=False)
    keywords = models.TextField(max_length=500, blank=True, null=True)

    def __unicode__(self):
        return self.question


class ArticleUserOwnership (models.Model):
    article = models.ManyToManyField(Article)
    user = models.ManyToManyField(User)

- 你可以在这里看到我挂钩到管理员用户表

Views.py:

from django.http import HttpResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate
from GeorgiaArticleManager.models import Article, ArticleUserOwnership
from django.shortcuts import render

def myarticles(request):
if request.user.is_authenticated():

    # articles of admin with id= 1
    my_articles = ArticleUserOwnership.objects.filter(user=1)
    context = {'my_articles': my_articles}


return render(request, 'template/myview.html', context)

myview.html:

ul
{% for ArticleUserOwnership in my_articles %}
li{{ ArticleUserOwnership }}/li
{% endfor %}
/ul

以上摘要:
ArticleUserOwnership.objects.filter(user = 1)返回一个对象,当我在myview.html上显示它时,我只是得到了ArticleUserOwnership对象'。我确定这是正确的退回对象但是,我想看看返回的Article.question。例如,Admin拥有测试标题1'我希望看到这篇文章问题字段正确显示。

2 个答案:

答案 0 :(得分:1)

my_articles = ArticleUserOwnership.objects.filter(user=1)

为您提供ArticleUserOwnership个实例的列表。如果你想要文章列表,请尝试这样做:

auo = ArticleUserOwnership.objects.get(user=1)  # could raise DoesNotExist
my_articles = auo.article.all()  # you should rename this field 'articles'

然而,ArticleUserOwnership模型并没有真正意义,我的猜测是你真正想做的是:

from django.db import models
from django.contrib.auth.models import User

class Article (models.Model): 
    question = models.CharField(max_length=255, unique=True, blank=False)
    keywords = models.TextField(max_length=500, blank=True, null=True)
    owners = models.ManyToManyField(User, related_name='owned_articles')

    def __unicode__(self):
        return self.question

然后您可以像这样访问您的数据:

my_articles = user.owned_articles.all()

有关如何使用ManyToManyFields的详细信息,请参阅documentation

答案 1 :(得分:0)

试试这个:

class ArticleUserOwnership (models.Model):
    article = models.ManyToManyField(Article)
    user = models.ManyToManyField(User)

    def __unicode__(self):
        return self.article

OR

def __unicode__(self):
    return self.article.question