Reputation: 59
I can't make a simple query working although I follow the docs https://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups.
models.py
class Course(models.Model):
name = models.CharField(max_length=30, unique=True, blank=False)
code = models.CharField(max_length=10, unique=True, blank=False)
def __str__(self):
return self.name
class User(models.Model):
...
courses = models.ManyToManyField(Course)
I registered an user, whose name is "a" and a course, which is called "mathématique" but I got this in the shell :
>>> User.objects.all()
[<User: a>]
>>> User.objects.filter(courses__name__contains='mathématique')
[]
>>> User.objects.filter(courses__name__in='mathématique')
[]
It always return an empty list and I can't understand why. When I see the administration I can see a User
who has a "mathématique" course.
EDIT
forms.py
from user.models import User, Course
class UserForm(forms.ModelForm):
cours_choices = forms.ModelChoiceField(queryset=Course.objects.all())
class Meta:
model = Offer
fields = ('cours_choices', 'faculty', 'description')
EDIT2
Okay, the problem is solved. The above queries works fine. I don't know why it's working now but I suspect the culprit could be a confusion about the name "cours", which was used for the class and the field
Upvotes: 0
Views: 125
Reputation: 2718
What if you remove "course = models.ManyToManyField(Course)" from class User and move it to class Course as follows "course = models.ManyToManyField(User)" and do following query:
User.objects.filter(course__name__contains='mathématique')
please note I have changed (Course) to (User)
Upvotes: 1