Hello, everyone. I have a problem about django orm query a field which is a list of strings
For example, such a model
class Something(models):
name = models.CharField(.....)
tags = models.JSONField(default=[])
The tags
field records some tag information, which is a list of strings, such as ['tag1 ‘,’ tag2 ‘,’ tag3 ']
I want to know how to query the contents of tags within ‘tag1’ in this table or should i change the model design, seek help Q.Q thanks a lot!
The contains
operator will return members of Something
containing a specific tag.
e.g. To find all Something
having tag2
as a member of the list tags
:
somethings = Something.objects.filter(tags__contains='tag2')
Now, having said that, whether your model design should be changed depends upon your requirements for these tags.
What do these tags represent? How you plan to use them? It there a relationship between Something
and SomethingElse
based on those tags? Does 'tag1'
in instance_1
have the same meaning as 'tag1'
in instance_2
? Are there other attributes associated with these tags?
These are all questions that you would need to understand the answers to in order to most properly design your models.
1 Like
Thank you very much. I think I should try this method. I think I misunderstood the contains
method before. I thought it could only judge whether a string field contains a sub string. These labels are generally just the labels themselves, and nothing else is based on these labels. According to your suggestion, I think I should put it in this model. I’ll test the contains method and give you the results later. Thank you again for your answer.
This method is indeed effective, but with a little supplement, the query here is still fuzzy search. for instance.
instance_one tags is [“tag”]
instance_two tags is [ “tag1”, “tag2”]
instance_three tags is [“tag”, “tag1”, “tag2”]
filter(tags__contains=“tag”) result is all of them: instance_one, two, three…
I think contains
will search whether the searched string belongs to the substring of each element in the list.
I have tried iexact
. It works on the JSONField.
something = Something.objects.filter(tags__iexact="tag")
# something is instance_one and instance_three
This isn’t working for me, iexact
is not working for me
Welcome @tasawernawaz !
If you are having an issue with which you would like assistance, please open up a new topic with the details about what you’re trying to do, how you’re trying to do it, and what’s happening as a result.