2010-12-14 24 views
41

Mam sytuacji, gdzie chcę użyć opcji Meta z unique_together wymusić pewną regułę, oto model pośrednik:Django Unikalne Razem (z kluczy obcych)

class UserProfileExtension(models.Model): 
    extension = models.ForeignKey(Extension, unique=False) 
    userprofile = models.ForeignKey(UserProfile, unique=False) 
    user = models.ForeignKey(User, unique=False) 

    class Meta: 
     unique_together = (("userprofile", "extension"), 
          ("user", "extension"), 
          # How can I enforce UserProfile's Client 
          # and Extension to be unique? This obviously 
          # doesn't work, but is this idea possible without 
          # creating another FK in my intermediary model 
          ("userprofile__client", "extension")) 

i oto UserProfile:

class UserProfile(models.Model): 
    user = models.ForeignKey(User, unique=True) 
    client = models.ForeignKey(Client) 

Dzięki.

Odpowiedz

8

Moje rozwiązanie było użyć Django get_or_create. Używając get_or_create, pojawi się niepotrzebne get, jeśli wiersz już istnieje w bazie danych, a wiersz zostanie utworzony, jeśli nie istnieje.

Przykład:


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

Wystarczy być ostrożnym. To może się nie udać, jeśli korzystasz z transakcji (prawdopodobnie). – mlissner

Powiązane problemy