Ordering relationship results "Manytomanyfield" with the same table in Django

Asked

Viewed 244 times

1

I have the Many to Many relationship with the same table, and I need to order the result with the same creation sequence. ex: add basic Django, intermediate Django, advanced Django; It has q appears in this sequence in the visualization. I have tried {% for req in Course.requirements.all|dictsort:"id" %} in the view, but with no result. Someone could help me out. Thanks 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

inserir a descrição da imagem aqui

visualization

inserir a descrição da imagem aqui

1 answer

0


Problem solved!!!

The problem has been solved with the use of the package "Django-sortedm2m". In this way I was able to order the result in a simple and effective way.

installation

pip install django-sortedm2m

py Settings.

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!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.