简体   繁体   English

在Django中相对于父模型订购子模型

[英]order a child model with respect to parent model in Django

I have Problem and Solution model defined in my models.py . 我在models.py定义了ProblemSolution模型。 Solution has a foreignkey to the Problem model. Solution具有Problem模型的外键。 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. 我要创建类似www.example.com/problem/problem_id/solution/solution_number/ url,其中problem_id描述问题模型的主键, solution_number描述针对特定问题发布solution_number的顺序。 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. 换句话说,如果解决方案是给定问题的第一个解决方案,则其阶数应为1,而同一问题的第二个解决方案的阶数应为2。

This will allow me to access a solution to particular problem like Solution.objects.get(problem=problem, order=order) 这将允许我访问解决特定问题的解决方案,例如Solution.objects.get(problem=problem, order=order)

easy 简单

root urls.py 根urls.py

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

problem.urls.py problem.urls.py

from .views import solution

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

views.py 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. 不要在Foreignkey字段中按对象查询,最好使用_id ,在这种情况下不涉及Problem表。

you dont need order . 你不需要order ID is always asc ordered. ID始终按升序排列。

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

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