0

I have a function now to find a model instance based on matching the string which the model returns. This is obviously not efficient. I was wondering if Django has a method to find a model instance based only on the string rather than by filtering by the instance attributes.

def parse_book(book_name):
    for book in Book.objects.all():
        if str(book) == book_name:
            return book
5
  • how about Book.objects.get(name=book_name) or Book.objects.filter(book=book_name)? Commented May 9, 2014 at 13:22
  • This was a made up example. Its difficult to search on the real model without doing a few other model lookups and using them as keys Commented May 9, 2014 at 13:23
  • Provide a concrete example then. Commented May 9, 2014 at 13:23
  • The example clearly shows what I want to work around Commented May 9, 2014 at 13:24
  • + I'm asking if its possible, not if its the best programming practice Commented May 9, 2014 at 13:25

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, the string does have some value, its made up of some foreign keys I'd need to lookup each of them to get to the point where I could make a object.get call.
You may not need to look them up, if you know what tables they represent. Foreign keys should be indexed automatically. Databases are good at joining tables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.