1

我的目标是显示属于我的名为“管理员”的用户的文章的可读列表

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

问题:当我返回对象时,它是一个完全不可读且无用的对象表示。我正在考虑在这里为我的模型添加一个unicode () 方法,但我不知道如何!

模型.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)

-- 你可以在这里看到我正在连接到管理员用户表

视图.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。例如,管理员拥有“测试标题 1”,我希望看到这篇文章问题字段正确显示。

4

2 回答 2

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

于 2013-08-19T07:14:19.333 回答
0

尝试这个:

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

    def __unicode__(self):
        return self.article

或者

def __unicode__(self):
    return self.article.question
于 2013-08-19T06:55:59.263 回答