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

前端 未结 2 1251
暗喜
暗喜 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:36

    You can use

    Entry.objects.filter(name='name', title='title').exists()
    

    This will return to you true/false values. When you use count the orm generates query which will be executed much longer than in exists method. The get method will raise an exception when object does not exists.

    request.POST is a dictionary so to check db with it you use, i.e.:

    Entry.objects.filter(name=request.POST['name'], title=request.POST['title']).exists()
    

提交回复
热议问题