Django: check whether an object already exists before adding

后端 未结 5 761
半阙折子戏
半阙折子戏 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 17:51

    If you're using a recent version of Django, you can use the unique_together option to the UserToUserRole model, and then use the get_or_create() method Joe Holloway showed. This will guarantee that you can't get a duplicate.

    0 讨论(0)
  • 2021-01-31 17:52

    You can use get(), but you'll have to wrap it with try-except like this:

    try:
        obj = UserToUserRole.objects.get(from_user=current_user, to_user=user, role='follow')
    except UserToUserRole.DoesNotExist:
        # here write a code to create a new object
    
    0 讨论(0)
  • 2021-01-31 17:56

    If you are looking for a bool value

    UserToUserRole.objects.filter(
        from_user=current_user, to_user=user, role='follow'
    ).exists()
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-31 18:09

    There's a helper function for this idiom called 'get_or_create' on your model manager:

    role, created = UserToUserRole.objects.get_or_create(
        from_user=current_user, to_user=user, role='follow')
    

    It returns a tuple of (model, bool) where 'model' is the object you're interested in and 'bool' tells you whether it had to be created or not.

    0 讨论(0)
提交回复
热议问题