如何避免圆形django模型导入?

问题描述 投票:0回答:1

我有以下这些模型

# user profile models file
from ad.models import FavoriteAd
class UserProfile(models.Model):

    def get_user_favorite_ad(self):
        return FavoriteAd.objects.filter(fav_user=self)


# ad models file
from user_profile.models import UserProfile

class FavoriteAd(models.Model):
    fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)

我尝试过使用这些,但它给了我NameError UserProfile not found

# ad models files
class FavoriteAd(models.Model):
    fav_user = models.ForeignKey('user_profile.UserProfile', blank=False, on_delete=models.CASCADE)

也试过这些仍然得到模型没有准备好的错误

# ad models files
from django.apps import apps
UserProfile = apps.get_model('user_profile', 'UserProfile')
class FavoriteAd(models.Model):
    fav_user = models.ForeignKey(UserProfile, blank=False, on_delete=models.CASCADE)
python django django-models
1个回答
3
投票

你在FavoriteAd模型的get_user_favorite_ad方法中使用UserProfile

这就是你无法在FavoriteAd中导入它的原因,这导致循环导入。

要获取该用户最喜欢的广告,请使用favoritead_set获取related objects

# remove that import as well
# from ad.models import FavoriteAd

class UserProfile(models.Model):

    def get_user_favorite_ad(self):
        return self.favoritead_set.all()
© www.soinside.com 2019 - 2024. All rights reserved.