In the model there is a field with string values ​​separated by commas and there is a list with which you need to compare these values. Something like that

all = Post.objects.filter(cities__in=citylst) 

How can this be implemented - how to change field formats and then filter the records, where is the intersection of their lists with the given list?

  • To search for list intersections, lists are usually translated into sets, for example, ru.stackoverflow.com/questions/427942/… - Dmitry Erohin
  • And how to translate the field in the set in the filtering process? - Maksim

1 answer 1

I tried to bring my answer as close as possible to your question, there is no jungle nearby.

 class A: def __init__(self,par1): self.b = par1 # список с которым сравниваем list2 = ['2','4'] #Подготавливаем второй set для поиска пересечений set2 = set(list2) if __name__ == '__main__': #В all два объекта у которых есть строковое поле "b" разделенное запятыми all = A('1, 2, 3, 4, 5'), A('1, 2') for obj in all: #Подготавливаем первый set для поиска пересечений set1 = set(obj.b) #Находим пересечения' delta_set = set1 & set2 print(delta_set)