Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have a model with a FileField:

class Foo(models.Model):

    file = models.FileField(
        upload_to='files'
    )

What would be the best approach for getting an object of the model from the databse with the name of the file?

Something like:

try:
    foo = Foo.objects.get(
        file__name='bar.csv',
    )
except Foo.MultipleObjectsReturned:
    return something()
except Foo.DoesNotExist:
    return something_else()
process(foo)

I guess I could add a file_name field into the model and setting self.file_name = self.file.name in Foo.save(), but that seems cumbersome..?

question from:https://stackoverflow.com/questions/66052877/django-how-to-get-an-object-with-a-file-name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
173 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...