简体   繁体   中英

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

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:

{% 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:

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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