I have the following models:
class Sked(models.Model):
pass
class Class(models.Model):
class_key = models.CharField(max_length=20, null=True)
name = models.CharField(max_length=150)
class Sked_class(models.Model):
class_room = models.CharField(max_length=100, null=True)
sked = models.ForeignKey(Sked)
class_took = models.ForeignKey(Class)
class User(djmodels.User):
sked = models.ForeignKey(Sked, null=True)
I want to make a query that selects all the classes that a specific user is taking, but i still can’t get the idea of how to do it without using SQL, I already read this document https://docs.djangoproject.com/en/dev/topics/db/queries/ , but I still don’t get it, How can I span multi-valued relationships through this models?
You’re looking for two things – how to span foreign keys, and how to only return a unique set of classes that doesn’t include duplicates.
You span foreign keys using
__to separate the relationships, and usedistinct()on the query set to filter out duplicates. Remember that foreign key relationships work both ways with Django syntax, as the ORM will recognize reverse relationships. This should work:It’s unclear to me if you data model makes sense, however. I think this makes more sense:
Then you’d say: