英文:
Get value of a field from a foreigKey in Django Models
问题
现在,我有两个在我的Django数据库中的类:
class Test(models.Model):
sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL)
class SequenzaMovimento(models.Model):
nomeSequenza = models.CharField(max_length=50, blank=False, null=False)
serieDiMovimenti = models.TextField(blank=False, null=False, default="")
现在,每个Test
对象都可以关联到一个SequenzaMovimento
对象。不同的Test
对象可以关联到相同的SequenzaMovimento
对象。
现在,我知道我的Test
对象的主键。如何找到与Test
对象关联的SequenzaMovimento
对象中的serieDiMovimenti
?
我可以从Test
对象中获取sequenzaTest
:
testo_sequenza = Test.objects.get(pk=idObj)
testo_sequenza.sequenzaTest
但是我不知道如何访问serieDiMovimenti
。
英文:
I have two classes in my Database in Django
class Test(models.Model):
sequenzaTest = models.ForeignKey("SequenzaMovimento", null=True, on_delete=models.SET_NULL)
class SequenzaMovimento(models.Model):
nomeSequenza = models.CharField(max_length=50, blank=False, null=False)
serieDiMovimenti = models.TextField(blank=False, null=False, default="")
Now, every Test
object created can be associated with just one SequenzaMovimento
object. Different Test
objects can have the same SequenzaMovimento
Now, I know the primary key of my Test. How do I find the serieDiMovimenti
inside the SequenzaMovimento
object which is linked to the Test
object?
I can get the sequenzaTest
from the Test
object with
testo_sequenza = Test.objects.get(pk=idObj)
testo_sequenza.sequenzaTest
but I can't find to understand how access serieDiMovimenti
答案1
得分: 1
testo_sequenza = Test.objects.get(pk=idObj)
testo_sequenza.sequenzaTest.serieDiMovimenti
英文:
You could try:
testo_sequenza = Test.objects.get(pk=idObj)
testo_sequenza.sequenzaTest.serieDiMovimenti
答案2
得分: 1
这应该可以工作:
try:
testo_sequenza = Test.objects.get(pk=idObj)
except Test.DoesNotExist:
# 如果未找到,可以在这里执行程序需要执行的操作。如果在循环中,可以考虑使用 return 或 continue/break
print("Testo Sequenza not found")
sequenza_test = testo_sequenza.sequenzaTest
serie_di_movimenti = sequenza_test.serieDiMovimenti
此外,您还应该检查以下代码:
serieDiMovimenti = models.TextField(blank=False, null=False, default="")
因为如果您希望它是一个"可选字段",那么应该是 blank=True
。
英文:
This should work:
try:
testo_sequenza = Test.objects.get(pk=idObj)
except Test.DoesNotExist:
# do here what you need the program to do if not found. maybe a return if function or a continue/break if you're in a loop
print("Testo Sequenza not found")
sequenza_test = testo_sequenza.sequenzaTest
serie_di_movimenti = sequenza_test.serieDiMovimenti
Also you should check
serieDiMovimenti = models.TextField(blank=False, null=False, default="")
Because if you want it to be "optional field" then it would be blank=True
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论