Sagar Devkota
Sagar Devkota

Reputation: 1315

How do use Foreign Key in slug django

My Models:

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)

my Views

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)

Urls

url(r'^(?P<faculty>[\w-]+)/(?P<program>[\w-]+)/(?P<slug>[\w-]+)/$', profile, name='profile'),

Now I got the profile at host/1/1/sagar-devkota/ what I need is host/science/be/sagar-devkota/ Let assume science is a faculty and be is a program.

Upvotes: 0

Views: 1802

Answers (1)

Thameem
Thameem

Reputation: 3646

give slug field to both faculty and program model. And in filter use __ for related lookups.

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

you can do it by using with that name field too.

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

Upvotes: 1

Related Questions