NullBooleanField始终为True

时间:2016-05-14 19:08:16

标签: python django django-models django-database

请节省宝贵的时间并帮助我。

我的应用程序的想法是每个用户将收到一组相同的30张卡,然后他必须决定每张卡是否重要。

我有两个课程如下:

class Card(models.Model):
    card_number = models.IntegerField(unique=True)
    content = models.TextField(null=False)

    def display(self):
        return self.content

    def __str__(self):
        return "Card  " + str(self.card_number)


class Choice(models.Model):
    user = models.ForeignKey(User)
    card = models.ForeignKey(Card)
    is_important = models.NullBooleanField(default=None)

    class Meta:
        unique_together = ('user','card')

    def get_choices(user):
        return Choice.objects.filter(pk=user.pk)

    def __str__(self):
        return " %s : Card %d : %s" % (self.user.username, self.card.card_number, self.is_important)

在views.py中,当用户决定卡是否重要时:

    card_number= request.GET.get('card_number')
    is_important= request.GET.get('is_important')    
    user = request.user

    # assume that user=admin, card_number=1 and is_important is False

    if card_number != None and is_important != None:
        try:
            card = Card.objects.get(card_number=card_number)
            choice= Choice.objects.create(user=user, card=card, is_important=is_important)
            print(choice)  # return admin: Card 1: False 
            print(Choice.objects.get(card__card_number=card_number))  # return admin: Card 1: True
            print(choice)  # return admin: Card 1: False 
        except IntegrityError:
            print("User had done with this Card")

我不明白为什么:

print(choice)  # return admin: Card 1: False 

但是

print(Choice.objects.get(card__card_number=1))  # return admin: Card 1: True

谢谢!

2 个答案:

答案 0 :(得分:3)

is_important取自GET QueryDict作为(可能)非空字符串。当您将此类字符串作为(Null)BooleanField的参数传递时,ORM会将其转换为bool,并且由于非空字符串的计算结果为True,因此将其存储在'True'中。分贝。

假设您将'False''None'is_important作为is_important = request.GET.get('is_important') # this is a string is_important = {'True': True, 'False': False, 'None': None}[is_important] 的获取参数传递,您可以这样做:

.objects.create()

我应该补充说,.objects.get()返回的实例和get返回的实例不一定相同,即使create调用检索kwargs调用的db记录也是如此。 {1}}致电。前者仍将具有作为'False'传递的属性(如字符串BooleanField),而后者将具有从数据库中检索的属性(因此具有bool的值现在将被转换为choice = Choice.objects.create(user=user, card=card, is_important=is_important) # choice.is_important = 'False' choice = Choice.objects.get(user=user, card=card, is_important=is_important) # choice.is_important = True (= bool('False')) ):

exports.list = function(req, res) {
Annonce.find().sort('-created').populate('user', 'displayName').exec(function(err, annoncer) {
    Land.find().sort('-created').populate('user', 'displayName').exec(function(err, lande){
    Aktivitet.find().sort('-created').populate('user', 'displayName').exec(function(err, aktiviteter){
    var all = lande.concat(annoncer,aktiviteter);
    res.jsonp(all);
    });
  });
 });
};

答案 1 :(得分:1)

除了schwobaseggl的答案(另一种方式),你最好使用Django formscleaned_data来防止这些并发症。