Django: check whether an object already exists before adding

后端 未结 5 762
半阙折子戏
半阙折子戏 2021-01-31 17:19

This is a pretty simple Django question, but I can\'t find the answer in the Django docs, despite lots of hunting!

How do I check whether an object already exists, and o

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 18:01

    If you want the check done every time before save you could use the pre save signal to check, http://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.pre_save

    Alternatively in the model you could specify unique=True for the property that determines whether an item is the same item, this will cause an Exception (django.db.IntegrityError) to be thrown if you try to save the same thing again.

    If you have more than one field together that makes something unique you'll need to use unique_together in the Meta inner class http://docs.djangoproject.com/en/dev/ref/models/options/#unique-together

提交回复
热议问题