2

我在不同的应用程序目录中有 2 个models.py 文件:users.models.py 和friends.models.py。

有一个问题:如果某个用户从 UserProfile 模型中删除,他的所有友谊网络也必须与他一起删除。这是很自然的。

但是当我将 Friendship 导入 users.model.py 时出现错误:Cannot import name Friendship

我了解由于在这两个文件中相互导入而出现错误,并且我知道我可以借助信号轻松解决此问题,但我不知道如何以正确的方式解决。

有人可以在这种特殊情况下提供帮助吗?

在 users.models.py 中:

from friends.models import Friendship

class UserProfile(models.Model):
    username = models.Charfield(max_length=50)
    ...

    def delete(self, *args, **kwargs):
        Friendship.objects.remove_all(self)
        self.delete(*args, **kwargs)

在friends.models.py中:

from users.models import UserProfile

class FriendshipManager(models.Manager):
    def remove_all(self, user):
        usr = Friendship.objects.get(user=user).friends
        frs = [i.user for i in usr.all()]
        for fr in frs:
            usr.remove(fr)

class Friendship(models.Model):
    user = models.Foreignkey(UserProfile)
    friends = models.ManyToManyField('self')

    objects = FriendshipManager()

提前致谢!!!

4

2 回答 2

1

这是我通常做的,你可以很容易地重构它来用你的模型来实现

from django.db import models
from django.db.models.signals import post_save, post_delete
from django.contrib.auth.models import User

# App specific


class UserProfile(models.Model):
    """
    Adds a basic UserProfile for each User on the fly.
    """
    user = models.OneToOneField(User)
    avatar = models.ImageField(upload_to='example/somewhere', blank=True)

    def __str__(self):
          return "%s's profile" % self.user

    def get_avatar(self):
        return '/'+self.avatar

    def clean_avatar(self):
        # TODO: imagekit
        pass

    class Meta:
        app_label = 'users'

    def save(self, *args, **kwargs):
        if self.id:
            this = UserProfile.objects.get(id=self.id)
            if this.avatar:
                if this.avatar != self.avatar:
                    this.avatar.delete(save=False)
        super(UserProfile, self).save()

def create_user_profile(sender, instance, created, **kwargs):
    if created:
       profile, created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_user_profile, sender=User)


def UserProfileDelete(instance, **kwargs):
    """
    Documentatie
    """
    instance.avatar.delete(save=False)

post_delete.connect(UserProfileDelete, sender=UserProfile)
于 2011-10-28T14:43:27.857 回答
1

不需要信号,只需使用神奇的 *_set 属性。它将在运行时定义,因此您不必担心循环导入。

朋友/models.py

from users.models import UserProfile

class Friendship(models.Model):
    user = models.Foreignkey(UserProfile)
    friends = models.ManyToManyField('self')

用户/模型.py

class UserProfile(models.Model):
    username = models.Charfield(max_length=50)
    ...

    def delete(self, *args, **kwargs):
        for f in self.friendship_set.all():
            f.delete()
        super(self.__class__, self).delete(*args, **kwargs)
于 2011-10-28T14:44:57.980 回答