我有以下这些模型
# 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)
你在
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()