简体   繁体   English

Django查询自指多对多关系

[英]Django Querying Self-referential Many-To-Many relations

I am trying to get a list of all manuscripts in my db, print out the shelfmarks for each of them and in case that they are linked to other manuscripts also print out the shelfmarks of those manuscripts. 我试图获取数据库中所有手稿的列表,打印出每个手稿的货架标记,并且如果它们链接到其他手稿,还可以打印出这些手稿的货架标记。

Here is what my models look like: 我的模型如下所示:

class MSS(models.Model):
    shelfmark = models.CharField(max_length=50)
    MSSLink = models.ManyToManyField('self',through='MSSLink',symmetrical=False)
    [...]

class MSSLink(models.Model):
    link1 = models.ForeignKey('MSS', related_name='First_MSS')
    link2 = models.ForeignKey('MSS', related_name='Second_MSS')
    [...]

Here is the code in views.py 这是views.py中的代码

def show_all_MSS(request):
    all_MSS = MSS.objects.select_related().all() # get all MSS     
    t = loader.get_template('list.html')
    c = Context({'all_MSS': all_MSS, })
    return HttpResponse(t.render(c))

The question is then what to do in my template. 然后的问题是在模板中该怎么做。 I thought about doing something like this, but I don't know how I can test whether the current MS in the for-loop has been linked to another MS and if so how to display those shelfmarks: 我曾考虑过要做这样的事情,但是我不知道如何测试for循环中的当前MS是否已链接到另一个MS,如果是,如何显示这些架子标记:

{% if all_MSS %}
    <ul>
    {% for i in all_MSS %}
        <li><a href="/MSS/{{ i.shelfmark}}/">{{ i.shelfmark }}</a></li>
            {% if i.MSSLink %}
            <p>This MS is linked to the following MSS: {{ i.MSSLink.link1 }}</p>
            {% endif %}
    {% endfor %}
    </ul>
{% else %}
    <p>No MSS found</p>
{% endif %}

Your models are a bit complicated - you can probably get rid of MSSLink: 您的模型有点复杂-您可能可以摆脱MSSLink:

class MSS(models.Model):
    shelfmark = models.CharField(max_length=50)
    links = models.ManyToManyField('self', symmetrical=False, blank=True)

    def __unicode__(self):
        return self.shelfmark

and add this to your template: 并将其添加到您的模板中:

{% if i.links.all %}
<ul>
    {% for l in i.links.all %}
        <li><a href="/MSS/{{ l.shelfmark}}/">{{ l.shelfmark }}</a></li>
    {% endfor %}
</ul>
{% endif %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM