Django从ManyToManyField反向查找OneToOneField

时间:2013-10-22 11:16:48

标签: python database django

我正试图通过Django中相当复杂的查找来访问特定字段。我想搜索一个链接到Poem模型的ManyToManyField标签,而该模型又通过带有OneToOneField的UserPoem模型链接。我无法解决如何做到这一点:

class Poem(models.Model):
    title = models.CharField(max_length=256)
    thetext = models.TextField()

class UserPoem(models.Model):
    poem = models.OneToOneField(Poem, related_name='u_poem')
    date = models.DateField()
    user = models.ForeignKey(User)

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)
    poems = models.ManyToManyField(Poem)`

所以给了一个标签,我想获得涉及该标签中诗歌标题文本的信息以及用户,诗歌的日期等等。我尝试了各种涉及select_related的方法,但只是无法破解它。这是(不工作)标签请求:

def tag_page(request, tag_name):
    tag = get_object_or_404(Tag, name=tag_name)
    poems = tag.poems.order_by('-id').select_related('u_poem')

我对Django的关系工作方式感到困惑。自从我决定将诗歌表模型分成两部分之后,我就遇到了无数问题。

这不会返回错误;它似乎没有从UserPoem / u_poem表中返回任何信息。

1 个答案:

答案 0 :(得分:1)

在你的位置我会这样做:

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)

class Poem(models.Model):
    title = models.CharField(max_length=256)
    thetext = models.TextField()
    tags   = models.ManyToManyField(Poem)

所以:

def tag_page(request, tag_name):
    poems_sets = []
    tag = get_object_or_404(Tag, name=tag_name)
    poems = Poem.objects.filter(tags__name=tag).order_by('-id')             
    for p in poems:                
        usersp = UserPoem.objects.filter(poem=p)
        for u in usersp:
            poems_sets.append((p, u))
    return locals() 

模板:

{% for poem,usersp in poems_sets %}
    {{poem.title}}
    {{poem.thetext}}
    {% for u in usersp %}
        {{u.date}}
        {{u.user}}
    {% endfor %}
{% endfor %}