如何在slug django中使用Foreign Key

时间:2017-04-23 03:00:34

标签: django

我的模特:

pre_randomize

我的观点

class Faculty(models.Model):
    name = models.CharField(max_length=30)


class Program(models.Model):
    name = models.CharField(max_length=30)
    faculty = models.ForeignKey(Faculty)


class Student(models.Model):
    name = models.CharField(max_length=30)
    slug = models.SlugField(max_length=30, unique=True)
    faculty = models.ForeignKey(Faculty)
    program = models.ForeignKey(Program)

网址

def profile(request, slug, faculty, program):
    template_name = 'profile.html'
    infor = get_object_or_404(Candidate, slug=slug, faculty=faculty, program=program)
    context = {'title': infor.name}
    return render(request,template_name,context)

现在我在host / 1/1 / sagar-devkota获得了个人资料/我需要的东西是host / science / be / sagar-devkota /假设科学是一个教师,并且是一个程序。

1 个答案:

答案 0 :(得分:1)

为教师和项目模型提供slug字段。并在过滤器中使用__进行相关查找。

infor = get_object_or_404(Candidate, slug=slug, faculty__slug=faculty, program__slug=program)

您也可以使用该name字段来完成此操作。

infor = get_object_or_404(Candidate, slug=slug, faculty__name=faculty, program__name=program)