Sorting relationship results "ManyToManyField" with the same table in Django

0

I have the Many to Many relationship with the same table, and I need to sort the result with the same creation sequence. ex: add Django basics, Django intermediate, Django advanced; You have this q appears in the preview. I've already tried {% for req in course.requirements.all | dictsort: "id"%} in the view but no result. Someone could give me a hand. Thank you very much in advance. Thank you ...

model.py:

class Course(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    requirements = models.ManyToManyField("self", blank=True, symmetrical=False)
    created_at = models.DateTimeField(auto_now_add=True)

admin.py

class CourseContentInline(admin.TabularInline):
    model = CourseContent

class CourseAdmin(AjaxSelectAdmin):
    list_display = ('name')
    search_fields = ['id', 'name']
    list_filter = ['created_at']
    prepopulated_fields = {"slug": ("name",)}
    inlines = (CourseContentInline,)
    form = make_ajax_form(Course, {
        'requirements': 'courses',
    })

admin.site.register(Content, ContentAdmin)

view.py

def details(request, slug):
course = get_object_or_404(Course, slug=slug)
course_content = CourseContent.objects.filter(course=course)

context = {
    'course': course,
    'course_content': course_content,
}

return render(request, 'portal/courses/details.html', context)

details.html

<aside class="col-lg-3">
{% if course.requirements.count >= 1 %}
    <article class="content-info">
        <h2>Pré-Requisitos</h2>
        <hr>
        <p>
            {% for req in course.requirements.all %}
                - <a href="{% url 'portal_courses_details' req.slug %}">{{ req.name }}</a><br>
            {% endfor %}
        </p>

    </article>
{% endif %}
</aside>

admin area

Preview

    
asked by anonymous 28.09.2016 / 15:21

1 answer

0

Problem solved !!!

The problem was solved by using the " django-sortedm2m package." That way I was able to sort the result in a simple and effective way.

installation

pip install django-sortedm2m

settings.py

INSTALLED_APPS = [
    'sortedm2m',
]

model.py

from sortedm2m.fields import SortedManyToManyField

class Course(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField()
    requirements = SortedManyToManyField("self", blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

create and run migrations

./manage.py makemigrations
./manage.py migrate

Problem solved !!!

    
30.09.2016 / 17:52