Skip to main content
 首页 » 编程设计

python之objects.all() 不返回 Django 中的任何对象

2024年08月26日36qq78292959

我在 models.py 中有以下模型:

from django.contrib.auth.models import User 
from django.db import models 
 
class Usertypes(models.Model): 
    user = models.OneToOneField(User) 
    usertype = models.TextField()                    
 
    def __unicode__(self): 
        return self.user_name 
 
class Games(models.Model): 
    name = models.CharField(max_length=100,unique=True) 
    category = models.CharField(max_length=100) 
    url = models.URLField() 
    developer = models.ForeignKey(User) 
    price = models.FloatField() 
 
    def __unicode__(self): 
        return self.name 
 
class Scores(models.Model): 
    game = models.ForeignKey(Games) 
    player = models.ForeignKey(User) 
    registration_date = models.DateField(auto_now=False, auto_now_add=False) 
    highest_score = models.PositiveIntegerField(null=True,blank=True) 
    most_recent_score = models.PositiveIntegerField(null=True,blank=True) 
 
    def __unicode__(self): 
        return self.most_recent_score 

我现在正在创建所有 3 种类型的对象。我之前创建了一些 User 和 Games 对象,所以当我运行以下命令时,将获得如下输出:

>>> u = User.objects.all() 
>>> u.count() 
5 
>>> g = Games.objects.all() 
>>> g.count() 
9 

现在,我正在尝试使用以下命令创建一些 Scores 对象。输出如下:

>>> fifa = Games.objects.get(pk=18) 
>>> user1 = User.objects.get(id=2) 
>>> user2 = User.objects.get(id=7) 
>>> user3 = User.objects.get(id=9) 
>>> p1 = Scores(game=fifa,player=user1,registration_date='2015-01-29') 
>>> p2 = Scores(game=fifa,player=user2,registration_date='2014-12-21') 
>>> p3 = Scores(game=fifa,player=user3,registration_date='2015-01-29') 
>>> user1 
<User: admin> 
>>> fifa 
<Games: Games object> 
>>> p1 
<Scores: Scores object> 
>>> p2 
<Scores: Scores object> 
>>> p3 
<Scores: Scores object> 

问题是:

>>> s = Scores.objects.all() 
>>> s.count() 
0 

我不明白为什么尽管创建了 3 个 Scores 对象,但 Scores.objects.all() 什么也不返回。有人可以帮忙吗?提前致谢!!

请您参考如下方法:

您从未将分数插入数据库(因此数据库当然无法将分数返回给您):

p1.save()  # This will save the object to the database 

请注意,您还可以使用 Scores.objects.create(...)(而不是 Score())。这将初始化一个对象并立即将其保存到数据库中:

p1 = Scores.objects.create(game=fifa,player=user1,registration_date='2015-01-29') 

现在这些方法会导致对数据库进行三个查询,这并不理想(您遇到了 3 次往返延迟)。

幸运的是,您可以使用 bulk_create 轻松优化和进行单个查询:

Scores.objects.bulk_create([ 
    Scores(game=fifa,player=user1,registration_date='2015-01-29') 
    Scores(game=fifa,player=user2,registration_date='2014-12-21') 
    Scores(game=fifa,player=user3,registration_date='2015-01-29') 
])