I would like to make the following query using the django model.
Is it possible to do it in a model class?
select
*
from
table t
where
(t.col1, t.col2) in (
("hoge", "fuga"),
("foo", "bar")
)
Quoted from https://qiita.com/lithtle/items/4517785c67843f601443
I thought the following would be fine, but
query_set=app_model.SampleModel.objects.filter(col1__in=['hoge','foo'], col2_in=['fuga','bar'])
If a record with (t.col1, t.col2) but ("hoge", "bar") exists, the incorrect result is returned.
Could you tell me the correct way?
By having columns that become composite keys connected by '_' as the main key,
Pseudo-multiple columns are allowed to use the in clause.
(The string length of the compound key is fixed.)
You must set the primary key on your own when inserting data, for example,
Record it as one of the workarounds.
from django.db import models
Class TableModel (models.Model):
id=models.CharField(primary_key=True, max_length=5)
col1 = models.CharField(max_length=2)
col2=models.CharField(max_length=2)
class Meta:
db_table='table'
model=TableModel(id='aa_xx', col1='aa', col2='xx')
model.save()
delete_list = ['aa_xx', 'bb_yy' ]
TableModel.objects.filter(id_in=delete_list).delete()
© 2024 OneMinuteCode. All rights reserved.