请帮助我。有一个带有循环导入的Django项目。项目的应用程序仅在一侧连接。但是有些函数使用没有参数的其他模型(用于模板),因此无法移动该函数。
我找到了两种解决方案: 第一种方法是在函数内部导入模型。 另一种将两个模型移动到一个文件中的方法。 两种解决方案都可以正常工作,但是哪个更好?
class InitialArticle(models.Model):
by = models.ForeignKey(get_user_model(), null=True, on_delete = models.SET_NULL)
category = models.ForeignKey(ArticleCategory, null=True, on_delete=models.CASCADE)
keywords = models.CharField(max_length = 110, unique = True)
def get_articles_of_initialarticle(self):
from article.models import Article
return Article.objects.filter(initial = self)
请帮助我找到更好的方法。也许还有其他解决方案?
答案 0 :(得分:0)
您可以像这样在Article.initial中添加related_name:
namespace enum_assignment
{
class Program
{
enum transportation
{ Car = 20,
Cab = 10,
Bus = 5,
Bicycle = 3,
};
static void Main(string[] args)
{
Console.WriteLine("Welcome to Kelvin Transit Center");
Console.WriteLine();
Type enumType;
enumType = typeof(transportation);
Console.WriteLine("Available transit methods:{0}", Environment.NewLine);
foreach (int value in Enum.GetValues(enumType))
Console.WriteLine("{0}:{1} dollars", Enum.GetName(enumType, value), value);
Console.WriteLine("Please enter your method of transporatation: Car,Bus,Cab,Bicycle");
Console.ReadLine();
transportation defaultMthd = transportation.Bicycle;
foreach (int value in Enum.GetValues(enumType))
switch(defaultMthd)
{
case transportation.Bicycle:
Console.WriteLine("Thank you for choosing {0},it is {1} every hour.",enumType, value);
break;
case transportation.Bus:
Console.WriteLine("Thank you for choosing {0},it is {1} every hour.",enumType, value);
break;
case transportation.Cab:
Console.WriteLine("Thank you for choosing {0},it is {1} every hour.",enumType, value);
break;
case transportation.Car:
Console.WriteLine("Thank you for choosing {0},it is {1} every hour.",enumType, value);
break;
}
Console.WriteLine();
Console.ReadKey();
}
}
之后,您可以像这样使用它:
class Article(...):
initial = models.ForeignKey(to='InitialArticle', related_name='articles')
也在模型中。ForeignKey可以使用字符串而不是像我写的那样导入模型
或者您可以在不添加related_name的情况下完成此操作。
默认的相关名称如下:article_set 如果您未设置related_name,则可以这样写:
initial_article = InitialArticle.objects.filter(...).first()
initial_article.articles.all() # return all articles which have foreign key to this article