英文:
How do I use foreign keys in Django?
问题
以下是翻译好的内容:
from django.db import models
# 创建你的模型
class ParentDeck(models.Model):
deck_name = models.CharField(max_length=300, primary_key=True)
def __str__(self):
return self.deck_name
class Flashcard(models.Model):
cardID = models.AutoField(primary_key=True)
question = models.CharField(max_length=300)
answer = models.CharField(max_length=300)
due_date = models.DateField()
parent_deck = models.ForeignKey(ParentDeck, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
这个问题困扰了我很长时间了。非常感谢你的帮助!我还是个初学者
我尝试查找解决方案并使用了ChatGPT [我了解到ChatGPT在这些任务上效果不好],但似乎没有什么作用。
英文:
from django.db import models
# Create your models here.
class ParentDeck(models.Model):
deck_name = models.CharField(max_length=300, primary_key=True)
def __str__(self):
return self.deck_name
class Flashcard(models.Model):
cardID = models.AutoField(primary_key=True)
question = models.CharField(max_length=300)
answer = models.CharField(max_length=300)
due_date = models.DateField()
parent_deck = models.ForeignKey(ParentDeck, null=True, on_delete=models.CASCADE)
def __str__(self):
return self.name
This has been killing me for a while now. Any help would be massively appreciated! I'm still a beginner
I tried looking up solutions and used ChatGPT [I've learnt that ChatGPT isn't great for these tasks], yet nothing seems to be working.
答案1
得分: 3
好的,以下是翻译好的内容:
好的,ForeignKey
是一种一对多关系。
你设置的方式意味着:
每个 Flashcard
都与一个特定的 ParentDeck
相关联。
每个 ParentDeck
都与多个或一组 Flashcard
相关联。
你可以通过以下方式访问关联的部分:
from app.models import Flashcard
f = Flashcard.objects.all().first()
print(f.parentdeck.deck_name)
以下是另一种方式,称为反向查找。
from app.models import ParentDeck
d = ParentDeck.objects.all().first()
linked_flashcards = d.flashcard_set.all()
print(linked_flashcards.first().question)
下划线加上“set”或 <object>_set
的语法是反向 Django 查找的默认实现。
其他关系的选项包括:
- 一对一关系
- 多对多关系
英文:
Ok so ForeignKey
is a One-to-Many relationship.
The way you have set it up means: <br>
Every single Flashcard
is linked to a specific ParentDeck
. <br>
Every ParentDeck
is linked to multiple, or a set of Flashcard
s.
You can access the linked part like this:
from app.models import Flashcard
f = Flashcard.objects.all().first()
print(f.parentdeck.deck_name)
The following is the other way round and called reverse lookup.
from app.models import ParentDeck
d = ParentDeck.objects.all().first()
linked_flashcards = d.flashcard_set.all()
print(linked_flashcards.first().question)
The syntax with underscore-"set" or <object>_set
is the default implementation for reverse django lookups.
Other options for relationships would be:
- one-to-one relationship
- many-to-many relationship
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论