On Jun 29, 4:57 am, Sam Walters <mr.sam...@gmail.com> wrote: > Hi > I am using django 1.0 to redevelop a website. > I have readhttp://docs.djangoproject.com/en/1.0/topics/db/queries/and cant > work out how to do my query except using raw sql. It would be great to be > able to use the django query api so i can stack queries more easily. > > Just one working example would be enough for me to be able to figure out the > rest of the syntax i need. > In this case the model is using a ForeignKey relationship between two > tables, thus is a one to many relationship. > > the model.py code exists here:http://pastebin.com/m7ddf3bb8 > > the views.py code exists here:http://pastebin.com/m78daa247 > > I would like to be able to replace the customer sql cursor.generate methods. > > Any help would be appreciated and allow me to discover a lot more about > django queries.
You don't need to explicitly join the tables - that's the whole point of having a foreignkey field in the model. However, there is one problem. It seems like your foreign key is on the wrong model. Surely each event has a single location, but a location can have many events? In which case, the FK should be from event to location. class Event (models.Model): .... location = models.ForeignKey(Event) Now, you can get the events like this: events = Event.objects.filter(start__gte=datetime.datetime.now ()).select_related() and iterate through in your template: {% for event in events %} {{ event.title }} - {{ event.location.name }} {% endfor %} The select_related() on the initial query is optional, but will get all the joined location data in one query and so cut down on database access. -- DR. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/django-users?hl=en -~----------~----~----~----~------~----~------~--~---