2013-03-23 63 views
4

當我使用Django Rest Framework刪除用戶時,關聯的UserProfile對象也被刪除。我想反向關係也是如此。我怎樣才能做到這一點?使用Django Rest Framework API刪除相關模型

我有一個代表用戶個人資料的Django模型。

class UserProfile(models.Model): 
    user = models.OneToOneField(User, related_name='profile') 
    preferred_name = models.CharField(max_lengths=100) 
    #other fields here 

這裏是我的看法:

class UserDetail(generics.RetrieveUpdateDestroyAPIView): 
    """ 
    API endpoint that represents a single user. 
    """ 
    model = User 
    serializer_class = UserSerializer 

class UserProfileDetail(generics.RetrieveUpdateDestroyAPIView): 
    """ 
    API endpoint that represents a single UserProfile 
    """ 
    model = UserProfile 
    serializer_class = UserProfileSerializer 

而串行:

class UserSerializer(serializers.HyperlinkedModelSerializer): 
    profile = serializers.HyperlinkedRelatedField(view_name = 'userprofile-detail') 

    class Meta: 
     model = User 
     fields = ('url', 'username', 'email', 'profile') 

class UserProfileSerializer(serializers.HyperlinkedModelSerializer): 

    class Meta: 
     model = UserProfile 
     fields = ('url', 'preferred_name', 'user') 

回答

2

你可以在你的用戶配置類覆蓋刪除的方法,這樣的:

class UserProfile(models.Model): 
    user = models.OneToOneField(User, related_name='profile') 
    preferred_name = models.CharField(max_lengths=100) 
    #other fields here 
    def delete(self, *args, **kwargs): 
     self.user.delete() 
     super(UserProfile, self).delete(*args, **kwargs) 
相關問題