1๐
โ
No, there is no way to do that more efficiently; you can either search using the database, in which case you need to search the fields in the model, or you can search the returned rows using Python, like you are doing.
(One way around this that some people use is /denormalization/ โ essentially saving the string with the model itself in the database, and then using it as an index.)
However, your string almost certainly has some relation to the fields that are in the model โ ideally, it is entirely determined by them. If that is true, then you can parse the string that you get to determine what the fields should be, and then do a lookup in the database based on those values.
Example code:
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
def __str__(self):
return self.title + ": " + self.author
def parse_book(book_name):
title, author = book_name.split(": ", 1)
try:
return Book.objects.get(title=title, author=author)
except Book.DoesNotExist:
return None
๐คIan Clelland
Source:stackexchange.com