每当我创建以后可以重用的DRY函数,然后在模型中使用它们时,我都会得到循环引用。
例如:
我有以下型号:
from social.services import get_top_viewed_posts
class Post(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
title = models.CharField('Post Title', max_length=255)
class ActivityUpdateEmail(models.Model):
sent = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now = True)
def send(self):
posts = get_top_viewed_posts()
我查看次数最多的帖子功能是另一个名为services.py的文件,因此我可以在其他地方访问它。看起来像:
from social.models import Post
def get_top_viewed_posts():
posts = Post.objects.filter(
pk__in=popular_posts_ids,
).order_by(
'-created_at'
)
return posts
然后我得到错误:
services.py", line 1, in <module>
from social.models import Post
ImportError: cannot import name 'Post'
如果我将其更改为:
交易= Action.objects.filter(content_type__pk = 35,created_at__gte = start_date,).values_list('object_id',flat = True)
popular_posts_ids = []
popular_posts = Counter(transactions).most_common()[:result_amount]
for dic in popular_posts:
popular_posts_ids.append(dic[0])
class ActivityUpdateEmail(models.Model):
sent = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now = True)
def send(self):
posts = Post.objects.filter(
pk__in=popular_posts_ids,
).order_by(
'-created_at'
)
这没问题。
如何使用这种干燥的抽象功能方法,然后在模型中使用它们?
相关分类