简体   繁体   中英

In Django ORM, how does one get_or_create for values in JSONField?

I am having a Django model like:

class Subscription(models.Model):
    data = JSONField(default=dict)

I want to do something like this:

data = {"product_id": 123, "available": False}
subscription, new = Subscription.objects.get_or_create(data__product_id=123, 
data__available=False)

I tried doing the above but it just set the field as empty dictionary.

Try this:-

models.py :-
class Subscription(models.Model):
    data = JSONField(db_index=True,null=True)

views.py:-
DictToStore = {"product_id": 123, "available": False}
subscription, new = Subscription.objects.get_or_create(data=DictToStore)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM