13 February

More tricks with foreign keys

Milestone 3 contains details about doing filters through foreign keys using the double underscore, as in:

Listing.objects.filter(user__username='chuck')

We also showed some ways to do this if you have access to a DB object in a Python variable. Suppose we assign the user chuck to variable u1:

u1 = User.objects.get(username='chuck')

Then we can do this to access Listings by chuck:

Listing.objects.filter(user = u1)

Or we can go in the reverse direction, from the User object to the Listings:

u1.listing_set.all()

The many-to-many relationship between Book and Course

The Book model has a ManyToManyField called course. This allows us to access lists of courses from a book, and lists of books from a course:

b = Book.objects.get(isbn='293750987')
b.course.all()
  → [<Course: ACC 102W Principles of Accounting-Lab>,
      <Course: ACC 129 Accounting Information Systems>]

c1 = Course.objects.get(prefix='ACC', number='102W')
c1.book_set.all()
  → [<Book: 293750987 CS Illuminated>]

If we need to add or remove objects from this relationship, here is the syntax:

c2 = Course.objects.get(prefix='CS', number='101')
b.course.add(c2)
b.course.all()
  → [<Course: ACC 102W Principles of Accounting-Lab>,
      <Course: ACC 129 Accounting Information Systems>,
      <Course: CS 101 Fund of CS & Informtn Sciences>]

b.course.remove(c1)
b.course.all()
  → [<Course: ACC 129 Accounting Information Systems>,
      <Course: CS 101 Fund of CS & Informtn Sciences>]

URLs with parameters

In class, we saw how to add URLs with parameters, such as using /book/NNN to display the book with id=NNN. From urls.py:

    url(r'^book/(\d+)/', 'app.views.showbook'),

The parentheses between the two slashes mean that this represents a parameter. The \d matches any digit character (09), and the + means there should be one or more of them. This syntax is part of a feature called Regular Expressions which are used in many systems besides Django and Python, and are worth learning.

Because we have a parameter in the URL, we have to add an extra parameter to our view function in app/views.py:

def showbook(request, id):
    b = Book.objects.get(id=id)
    return HttpResponse("%s<br>%s<br>%s<br>%s" %
                (b.isbn, b.title,
                 b.authors, b.publisher))

This view will print out the details of a book whose id is given in the URL. The id field of a DB object is automatically assigned, and is just an integer.

comments powered by Disqus

 

©2012 Christopher League · some rights reserved · CC by-sa