Answer the question
In order to leave comments, you need to log in
How to filter by list from ManyToMany?
There is a model with a field ManyToMany
. From POST
the request I get a list of pk records that are ManyToMany
attached to. It pk
is the object that is ManyToMany
attached to. I need to receive only those records which were in this model.
So I'm looking for them:
json_request = json.loads(request.body)
exists_list = json_request['addId']
exists_list.append(json_request['mainId'])
print(exists_list)
try:
exists_result = LinkedData.objects.filter(many__in=exists_list)
print(exists_result) >>> 5, 823, 186, 585
return HttpResponse(exists_result)
except LinkedData.DoesNotExist:
return HttpResponse('ok')
ManyToMany
are as pk
follows: 5, 823, 186, 585
exists_list
: [83, 663, 853, 5]
exists_result
contains the following entries: 5, 823, 186, 585
exists_list
body ). POST
So far, I've come up with to sort through QuerySet
and look for matches with exists_list
, and then what is not in exists_list
delete from QuerySet
. Maybe there is a crutch way to do everything right? class LinkedData(models.Model):
many = models.ManyToManyField(
ObjectDataFull,
related_name='many_related',
verbose_name='Много'
)
class Meta:
db_table = 'build_analyzer_linked_data'
def __str__(self):
return u', '.join([str(a.pk) for a in self.many.all()])
class LinkedInfo(models.Model):
linked_data = models.ForeignKey(
LinkedData,
on_delete=models.CASCADE,
related_name='linked_data_related'
)
full = models.ForeignKey(
ObjectDataFull,
on_delete=models.CASCADE,
related_name='unsorted_related'
)
main = models.BooleanField(
default=False,
null=False,
)
class Meta:
db_table = 'build_analyzer_linked_info'
exists_list = json_request['addId']
exists_list.append(json_request['mainId'])
exists_list = json_request['addId'].append(json_request['mainId'])
exists_list is None >>> True
{
"mainId": 5,
"addId": [83, 663, 853]
}
Answer the question
In order to leave comments, you need to log in
This is the basic functionality of Django, and in the first snippet you use it quite correctly. It is not clear why the filtering does not occur, without casting the models and the relevant state of the database.
Possible reasons:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question