如何使用Python 3.6中定义的类?
我需要在下面的“集合”类中请求类“产品”,以创建多对多连接。但是编译器说“产品”这个名字没有定义。有什么可能的方法吗如何使用Python 3.6中定义的类?,python,django,django-models,Python,Django,Django Models,我需要在下面的“集合”类中请求类“产品”,以创建多对多连接。但是编译器说“产品”这个名字没有定义。有什么可能的方法吗 class Collection(models.Model): products = models.ManyToManyField(Product, blank=True, on_delete=models.CASCADE) class Product(models.Model): collection = models.ManyToManyField(Coll
class Collection(models.Model):
products = models.ManyToManyField(Product, blank=True, on_delete=models.CASCADE)
class Product(models.Model):
collection = models.ManyToManyField(Collection, blank=True, on_delete=models.CASCADE)
我只需要将“产品”放在“集合”中,反之亦然。尝试声明class
Product
,然后再声明Collection
,然后像这样简单地使用它:
class Collection(models.Model):
products = models.ManyToManyField(Product, blank=True, on_delete=models.CASCADE)
对于产品,您可以考虑使用justuse字符串attr。像
'Collection'
一样,您可以通过使用字符串来修复未定义的错误:products=models.ManyToManyField('Product',…)
。但是,通常不会将多对多字段添加到这两个模型中。一旦您添加了products=models.ManyToManyField('Product',…)
,每个产品可以有多个集合,每个集合可以有多个产品,因此您不必添加collection=models.ManyToManyField(集合,…)
到产品
模型。如果我把产品放在集合中,我就会看到,集合中有这个产品。但是现在它没有发生这是django的事情,而不是python的事情,在类名周围使用引号将惰性地创建关系django admin不会为集合的产品创建关系(除非您使用。但是集合将包含产品。您可以使用collection.product\u set.all()签入django shell
请提供完整的错误消息,以及一个问题。该问题是否特定于/特定于Python 3.6?