How to check if something exists in a postgresql database using django?

前端 未结 2 1304
暗喜
暗喜 2021-02-02 08:58

I want to check to see if row in the database already contains a particular input. If it does already exist, prevent it from being added again, if not then add it like normal.

2条回答
  •  没有蜡笔的小新
    2021-02-02 09:51

    The answer to your question is "Yes". However, I think you should also investigate an alternative to querying the database; create a unique key on the set of fields you don't want duplicates to exist for.

    Now, to answer your question. Check out the Django docs for making a query:

    https://docs.djangoproject.com/en/dev/topics/db/queries/

    In short, if you have a data model for a Thing, Thing.objects is the interface for accessing queries. from the docs (using Blog Entry, which has a string field "headline" as an example):

    Entry.objects.get(headline__exact="Man bites dog")
    

    The full capabilities of the interface are what you would expect from a database (there is a rich set of comparisons to data other than exact matches). I'd suggest looking further into the documentation for your specific problem.

提交回复
热议问题