简体   繁体   中英

order a child model with respect to parent model in Django

I have Problem and Solution model defined in my models.py . Solution has a foreignkey to the Problem model. That is, a problem can have many solutions.

I want to create urls like www.example.com/problem/problem_id/solution/solution_number/ where problem_id describes the primary key of Problem model and solution_number describes the order in which the solution was posted for a particular problem. In other words, if a solution is first solution to a given problem, its order should be 1 and second solution to the same problem gets an order 2.

This will allow me to access a solution to particular problem like Solution.objects.get(problem=problem, order=order)

easy

root urls.py

urlpatterns = [
    url(r'^problem/', include('your.apps.problem.urls')
]

problem.urls.py

from .views import solution

urlpatterns = [
    url(r'^(?P<prob_id>\d+)/solution/(?P<sol_id>\d+)/$', solution)
]

views.py

def solution(request, prob_id, sol_id):
    sol = Solution.objects.get(problem_id=prob_id, pk=sol_id)

dont query by object in Foreignkey fields, better with _id which does not involve Problem table in this case.

you dont need order . ID is always asc ordered.

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