Django有许多字段持有用户自动填充



我正在从web上的json文件中提取数据,并在我的django数据库中更新它。我想跟踪与每个团队相关联的用户,但一旦用户加载页面,他们就会被添加到模型中。我该如何避免这种情况?

class Team(models.Model):
name = models.CharField(max_length=120)
abbreviation = models.CharField(max_length=3)
id = models.IntegerField(primary_key=True)
link = models.CharField(max_length=120)
wins = models.IntegerField(default=0)
losses = models.IntegerField(default=0)
ties = models.IntegerField(default=0)
points = models.IntegerField(default=0)
users = models.ManyToManyField(User)
def getTeams():
import requests
baseUrl = "https://statsapi.web.nhl.com/"
# INITALIZING THE DATA IN THE DATA DICTIONARY
r = requests.get(baseUrl + '/api/v1/teams')
originalData = r.json()
# i dont need the copyright, only care about the teams
originalData = originalData["teams"]
for team in originalData:
id = team["id"]
try:
databaseTeam = Team.objects.get(id = id)
except Exception:
Team.objects.create(id = id)
databaseTeam = Team.objects.get(id = id)
databaseTeam.name = team["name"]
databaseTeam.abbreviation = team["abbreviation"]
databaseTeam.link = team["link"]
databaseTeam.save()
print("done")
@login_required
def myTeamView(request):
t1 = Thread(target=getTeams)
t1.start()
return(render(request, "teams/myTeams.html", {}))

用户存储在请求中的user变量上,因此首先我们需要将其传递给getTeams方法。然后,我们使用Manytomany字段的方法add向其附加一条记录,在本例中为用户。

def getTeams(request):
import requests
baseUrl = "https://statsapi.web.nhl.com/"
# INITALIZING THE DATA IN THE DATA DICTIONARY
r = requests.get(baseUrl + '/api/v1/teams')
originalData = r.json()
# i dont need the copyright, only care about the teams
originalData = originalData["teams"]
for team in originalData:
id = team["id"]
try:
databaseTeam = Team.objects.get(id = id)
except Exception:
Team.objects.create(id = id)
databaseTeam = Team.objects.get(id = id)
databaseTeam.name = team["name"]
databaseTeam.abbreviation = team["abbreviation"]
databaseTeam.link = team["link"]
databaseTeam.save()
databaseTeam.users.add(request.user) # after save!!
print("done")
@login_required
def myTeamView(request):
t1 = Thread(target=getTeams, args=(request, ))
t1.start()
return(render(request, "teams/myTeams.html", {}))

相关内容

  • 没有找到相关文章

最新更新