协助Django模型关系

时间:2011-04-17 16:09:14

标签: python database django database-relations

    class Pinyin(models.Model):
    pinyinWord = models.CharField(max_length=200)
    englishWord = models.CharField(max_length=1000)
    englishPhrase = models.TextField()
    pinyinPhrase = models.TextField()
    def __unicode__(self):
        return u"%s | %s" % (self.pinyinWord, self.englishWord)

class Learned(models.Model):
    def __unicode__(self):
        return u"%s | %s | %s | %s" % (self.pinyinWord, self.user, self.date, self.learned) 
    pinyinWord = models.ForeignKey(Pinyin)
    user = models.ForeignKey(User)
    date = models.DateField()
    learned = models.BooleanField()

我是django的新手并为此编程并想要将Model Pinyin中的值添加到Model Learned中,但前提是它尚未添加到该特定用户的学习中但似乎无法准确掌握如何这样做。

例如,我想从拼音中获取一个值,如果Pinyin.id和User.id尚未在Learned中,则将该单词添加到Learned模型中,其中包含用户ID,今日日期和学习设置为False / 0

2 个答案:

答案 0 :(得分:1)

您可以使用模型元选项unique_together

class Learned(models.Model):
    pinyinWord = models.ForeignKey(Pinyin)
    user = models.ForeignKey(User)
    date = models.DateField()
    learned = models.BooleanField()
    class Meta:
        unique_together = ('user', 'pinyinWord')

答案 1 :(得分:0)

我希望这就是你所期待的:

uid = User.objects.get(username='Greg').id
pinyin = Pinyin.objects.get(pinyinWord='kuai')

learned, created = Learned.objects.get_or_create(pinyinWord=pinyin.pinyinWord, 
                                                                 user__id=uid)
if created:   # newly INSERTed Learned  instance
     learned.date = datetime.date.today()
     learned.learned = False
     learned.save()

Model.objects.get_or_create方法首先使用提供的参数尝试 Model.objects.get 调用。如果失败,将创建对象,创建将为True,否则创建为False。

由于这是两个字段的精确查找(例如,不是pinyinWord__contains),因此当没有Learned实例满足这两个字段时,它将失败。然后它就会被创建。

之后,您可以设置日期等,然后保存实例。