Django Unique Together (with foreign keys)

后端 未结 6 831
独厮守ぢ
独厮守ぢ 2020-11-28 11:35

I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here\'s the intermediary model:



        
6条回答
  •  暖寄归人
    2020-11-28 12:04

    My solution was to use Django's get_or_create. By using get_or_create, a useless get will occur if the row already exists in the database, and the row will be created if it does not exist.

    Example:

     
    extension = Extension.objects.get(pk=someExtensionPK)
    userProfile = UserProfile.objects.get(pk=someUserProfilePK)
    UserProfileExtension.objects.get_or_create(extension=extension, userprofile=userProfile)

提交回复
热议问题