如何将特定模型中的行与 django 中另一个模型中的字段绑定
我对以下(简化版)模型有问题:
Sponsor(models.Model):
sponsor_name = models.CharField()
Concerts(models.Model):
artist_name = models.CharField()
sponsor = models.ManyToMany(Sponsor)
我进入管理界面并添加一个新的赞助商,它会自动显示在任何音乐会上,所有赞助商都会显示在所有音乐会上。这不是我想要的,我希望一些赞助商参加一些音乐会。
我意识到这是一个人际关系问题。 我尝试过:
Sponsor(models.Model):
belongs_to = models.ForeignKey(Concerts)
sponsor_name = models.CharField()
Concerts(models.Model):
artist_name = models.CharField()
但现在我不能重复使用赞助商,我必须为每场音乐会添加一个新的赞助商。
I have a problem with the following (simplified version) models:
Sponsor(models.Model):
sponsor_name = models.CharField()
Concerts(models.Model):
artist_name = models.CharField()
sponsor = models.ManyToMany(Sponsor)
I go to the admin interface and add a new Sponsor, it automatically shows on any concert, all Sponsors show on all Concerts. That is not what I want, I want SOME sponsors to be on SOME concerts.
I realize this is a relationships problem.
I have tried:
Sponsor(models.Model):
belongs_to = models.ForeignKey(Concerts)
sponsor_name = models.CharField()
Concerts(models.Model):
artist_name = models.CharField()
But now I can't reuse sponsors, I have to add a new one for each Concert.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您在 django-admin 界面的
Concert
模型中实际选择的Sponsor
中可能的值是错误的。尝试这个 python manage.py shell ,然后 from yourapp.yourmodel import Concerts; Concerts.objects.sponsor_set.all()。
结果应仅包含该模型的选定
赞助商
(我打赌您会看到空列表)。I think you're mistaking possible values with actually chosen
Sponsor
inConcert
model in django-admin interface.Try this
python manage.py shell
and thenfrom yourapp.yourmodel import Concerts; Concerts.objects.sponsor_set.all()
.Result should contain only selected
Sponsors
for that model (I bet you'll see empty list).如果您希望每场音乐会有多个
Sponsor
,并且每个Sponsor
能够与多个Concert
关联,那么您需要使用ManyToManyField
而不是ForeignKey
。请参阅文档 https://docs.djangoproject.com/ en/dev/ref/models/fields/#manytomanyfield
问题可能在于您如何显示赞助商 - 请确保当您在模板中打印音乐会时,您没有选择所有赞助商,而是迭代
concert_instance.sponsor.all()
查询集。If you want each concert to have multiple
Sponsor
s, and eachSponsor
to be able to be associated with multipleConcert
s, then you will want to use aManyToManyField
rather than aForeignKey
.See the docs for that at https://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield
The problem is probably in how you are displaying your Sponsors--please be sure that when you're printing the concert out in your template, you're not selecting all Sponsors, but instead iterating over
concert_instance.sponsor.all()
queryset.