Hello, everyone. I have a problem about django orm query a field which is a list of strings
For example, such a model
name = models.CharField(.....)
tags = models.JSONField(default=)
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!
contains operator will return members of
Something containing a specific tag.
e.g. To find all
tag2 as a member of the list
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
SomethingElse based on those tags? Does
instance_1 have the same meaning as
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.
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…
containswill 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