【问题标题】:how to solve two model circular dependency in django如何在django中解决两个模型循环依赖
【发布时间】:2021-06-10 16:03:23
【问题描述】:

我在 django 项目 models.py 中有一个文件:

from django.db import models


class Product(models.Model):
    id = models.IntegerField(unique=True,primary_key=True)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length= 100000)
    price = models.FloatField()
    count = models.IntegerField(default=1)
    file_content = models.ManyToManyField(ProductImage, related_name='file_content', blank=True, null=True)

    offer= models.BooleanField(default=False)

    def __str__(self):
        return self.title

class ProductImage(models.Model):
    property_id = models.ForeignKey(Product,on_delete=models.CASCADE)
    image = models.FileField(upload_to='pics')
    

    def __str__(self):
        return '%s-image' % (self.property_id.title)

它说ProductImage没有定义,这很清楚,因为它在下面定义。如果我尝试像这样将其向上移动:


class ProductImage(models.Model):
    property_id = models.ForeignKey(Product,on_delete=models.CASCADE)
    image = models.FileField(upload_to='pics')
    

    def __str__(self):
        return '%s-image' % (self.property_id.title)

 
class Product(models.Model):
    id = models.IntegerField(unique=True,primary_key=True)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length= 100000)
    price = models.FloatField()
    count = models.IntegerField(default=1)
    file_content = models.ManyToManyField(ProductImage, related_name='file_content', blank=True, null=True)

    offer= models.BooleanField(default=False)

    def __str__(self):
        return self.title

现在它说 Product is not defined 。任何人都可以告诉我补救措施吗?

到目前为止我做了什么? 我尝试制作一个名为 img.py 的单独文件,class ProductImage 在那里写了。然后我尝试在这里导入它。现在它说:

Watching for file changes with StatReloader
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "c:\users\hussnain\appdata\local\programs\python\python39\lib\threading.py", line 954, in _bootstrap_inner   
    self.run()
  File "c:\users\hussnain\appdata\local\programs\python\python39\lib\threading.py", line 892, in run
    self._target(*self._args, **self._kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run
    autoreload.raise_last_exception()
  File "E:\UsamaComputer\env\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "E:\UsamaComputer\env\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    autoreload.check_errors(django.setup)()
  File "E:\UsamaComputer\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args, **kwargs)
  File "E:\UsamaComputer\env\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "E:\UsamaComputer\env\lib\site-packages\django\apps\registry.py", line 114, in populate
    app_config.import_models()
  File "E:\UsamaComputer\env\lib\site-packages\django\apps\config.py", line 301, in import_models
    self.models_module = import_module(models_module_name)
  File "c:\users\hussnain\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module 
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 790, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "E:\UsamaComputer\backend\frontend\models.py", line 2, in <module>
    from .img import ProductImage
  File "E:\UsamaComputer\backend\frontend\img.py", line 2, in <module>
    from .models import Product
ImportError: cannot import name 'Product' from partially initialized module 'frontend.models' (most likely due to a circular import) (E:\UsamaComputer\backend\frontend\models.py)

意味着我不能通过循环导入来欺骗他。你们可以帮助我吗?感谢阅读,接下来是解决它。

【问题讨论】:

    标签: python django django-models django-rest-framework django-views


    【解决方案1】:

    试着这样做

    class Product(models.Model):
        id = models.IntegerField(unique=True,primary_key=True)
        title = models.CharField(max_length=200)
        description = models.TextField(max_length= 100000)
        price = models.FloatField()
        count = models.IntegerField(default=1)
        file_content = models.ManyToManyField("ProductImage", related_name='file_content', blank=True, null=True)
    
        offer= models.BooleanField(default=False)
    
        def __str__(self):
            return self.title
    
    class ProductImage(models.Model):
        property_id = models.ForeignKey("Product",on_delete=models.CASCADE)
        image = models.FileField(upload_to='pics')
    

    【讨论】:

    • 非常感谢。有效 。如果你在我面前,我会拥抱你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    • 2016-09-21
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    相关资源
    最近更新 更多