协助 Django 模型关系
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 和编程方面的新手,希望将拼音模型中的值添加到学习模型中,但前提是该值尚未添加到特定用户的学习中,但似乎无法准确掌握如何做到这一点。
例如,我想从 Pinyin 获取一个值,如果 Pinyin.id 和 User.id 尚未在 Learned 中,则将该单词添加到 Learned 模型中,并将用户 id、今天的日期和 learned 设置为 False/0。
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()
I am new to django and programming for that matter and want to add a value from Model Pinyin to Model Learned but only if it has not already been added to learned for that specific user but can't seem to grasp exactly how to do this.
For example, I want to grab a value from Pinyin and if Pinyin.id and User.id are not already in Learned, then add the word to the Learned model with the user id, todays date and learned set to False/0.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用模型元选项
unique_together
:You could use the model meta option
unique_together
:我希望这就是您正在寻找的:
Model.objects.get_or_create 方法首先尝试使用提供的参数进行 Model.objects.get 调用。如果失败,则将创建该对象,并且created将为True,否则created为False。
由于这是对两个字段的精确查找(例如不是 pinyinWord__contains),因此当没有满足这两个字段的 Learned 实例时,它将失败。然后它就被创建了。
之后您可以设置日期等并保存实例。
I hope this is what you are looking:
The Model.objects.get_or_create method first tries a Model.objects.get call with the provided arguments. If it fails, the object will be created and created will be True, otherwise created is False.
Since this is an exact lookup (not pinyinWord__contains for example) for both fields, it will fail when there is no Learned instance that satisfies both fields. Then it gets created.
After that you can set the date and so on and save the instance.