Reputation: 1814
I've a JSONField in my model which is storing below types of data.
[
{
"name":"Name A",
"type":"Type1",
"class_type":"Class A"
},
{
"name":"Name B",
"type":"Type1",
"class_type":"Class A"
},
{
"name":"Name C",
"type":"Type2",
"class_type":"Class A"
}
]
I've tried with the example of django documentation. But still return Null
I've tried with SampleCategory.objects.filter(books__name = 'Name A')
Upvotes: 1
Views: 1030
Reputation: 52028
As per documentation, you can use book__name
when you define the json data like this:
data = {
"name":"Name A",
"type":"Type1",
"class_type":"Class A"
}
SampleCategory.objects.create(books=data)
SampleCategory.objects.filter(books__name = 'Name A')
Or if you define it like this as array:
data = [
{
"name":"Name A",
"type":"Type1",
"class_type":"Class A"
},
{
"name":"Name B",
"type":"Type1",
"class_type":"Class A"
},
{
"name":"Name C",
"type":"Type2",
"class_type":"Class A"
}
]
SampleCategory.objects.create(books={'book':data})
SampleCategory.objects.filter(books__0__name = 'Name A')
If you have an array with simillar structured dictionary, then consider making separate model fields and create different entries. Like this:
class Book(models.Model):
name = models.CharField(max_length=255)
type = models.CharField(max_length=255)
class_type = models.CharField(max_length=255)
And use it as FK to SampleCategory
:
class SampleCategory(models.Model):
books = models.ForeignKey(Book)
Then you can query like the way you want in the given question( for example SampleCategory.objects.filter(books__name = 'Name A')
). Hope it helps.
Upvotes: 1