如何访问Django外部的Django关系?



我在django中有一个小项目,我需要访问django项目外的django关系。

我想通过player.logs.all()等命令获得与玩家相关的所有日志的querySet。获得querySet通过player.logs.all()工作时,我做它在django shell和当我做它在views.py,但它不工作从外部文件,即使当我设置django连接正确

models.py

class Log(models.Model):
name = models.CharField(max_length=50)
link = models.PositiveIntegerField(default=0, primary_key=True)

class Meta:
app_label = 'stats'

def __str__(self):
return self.name
class Player(models.Model):
logs = models.ManyToManyField(Log)
name = models.TextField()
steamid3 = models.CharField(max_length=20, primary_key=True)
class Meta:
app_label = 'stats'
def __str__(self):
return self.steamid3

外部test.py

import django
from django.conf import settings
settings.configure(
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
'NAME': 'stats',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
}
)
django.setup()
from stats.models import *
l = Log.objects.all()  #Works
players = Player.objects.all() #Works
player = Player.objects.get(pk='[U:1:92778910]') #Works
print(player.logs.all()) #Does not work

运行test.py后出现错误

django.core.exceptions.FieldError: Cannot resolve keyword 'player' into field. Choices are: link, name

解决方案

需要导入django的初始设置,而不是手动配置。如下所示

test.py

import django
import os
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tf2stats.settings")
django.setup()
from stats.models import *
player = Player.objects.get(pk='[U:1:100146668]')
print(player.logs.all())

相关内容

  • 没有找到相关文章

最新更新