I have the following Django Model -
class M(models.Model):
...
disp_name = models.CharField(max_length=256, db_index=True)
...
class XX(models.Model):
x = models.ForeignKey(User)
y = models.ForeignKey(M, unique=True)
Now in my views.py, I want to do a partial string match on all items in XX
with the field y.disp_name.
Normally one would do this - M.objects.filter(disp_name__istartswith='string')
But here M
is a foreignkey in Model XX
. So if I do XX.objects.filter(y.disp_name__istartswith='string')
I get an error.
Also, this too fails -
u = User.objects.get(id=1)
u.xx_set.filter(y.disp_name__istartswith='string')
Exception that I get says is - SyntaxE开发者_开发技巧rror: keyword can't be an expression (<console>, line 1)
How to do this?
I wish you had used proper field names rather than X, Y and M - it's really hard to follow.
But in any case, you should always use the double-underscore syntax to follow relations on the left hand side of the filter expression:
XX.objects.filter(y__disp_name__istartswith='string')
(The technical reason for this is that the parameters to filter
are actually keyword arguments to a function, so the left-hand side of that has to be a string rather than an expression.)
精彩评论