【问题标题】:How to use ForeignKey get model field如何使用 ForeignKey 获取模型字段
【发布时间】:2015-11-30 17:52:38
【问题描述】:
class hotel(models.Model):
    hotel_name = models.CharField(max_length=200)

class Sell(models.Model):
    hotel = models.ForeignKey("hotel")
    sell_name = models.CharField(max_length=200)

class Orderform(models.Model):
    buy_choices = [(data.id+1, data.hotel_name) for data in hotel.objects.all()]
    buy_hotel_id = models.IntegerField(choices=buy_choices,default=1)

class Selled(models.Model):
    orderform = models.ForeignKey("Orderform")
    sell_id = models.IntegerField()
    sell_count = models.IntegerField(default=1)

我希望sell_id 使用选择

buy_choices = [(data.id+1, data.sell_name) for data in hotel.objects.get(id=buy_hotel_id).sell_set.all()]
sell_id = models.IntegerField(choices=sell_choices,default=1)

但我不知道如何获得buy_hotel_id

我想使用hotel.objects.get(id=buy_hotel_id)

例子

<hotel:1> have [<sell:banana>,<sell:apple>]
<hotel:2> have [<sell:grapes>,<sell:starfruit>]

如果buy_hotel_id1

想要结果[&lt;sell:banana&gt;,&lt;sell:apple&gt;]

我试试Sell.objects.all() 获取[&lt;sell:banana&gt;,&lt;sell:apple&gt;,&lt;sell:grapes&gt;,&lt;sell:starfruit&gt;] 这不是我想要的结果

【问题讨论】:

  • 您想获得酒店的销售物品?问题很不清楚
  • +1 to taesu,此外,我不明白你为什么要这样做data.id+1(这会给你错误的id,甚至是不存在的id),而且是动态的字段的选择比这要复杂一些。在表单中查看 ForeignKey.limit_choices_to 和 ModelChoiceField。
  • 采纳 Paulo 的答案,hotel.sell_set.filter(pk=1) 不会为您的示例得到正确的结果吗?

标签: python django django-models


【解决方案1】:

我没有明白你想要做什么。你能更好地解释一下吗? 不会是这样吧?

sell_choices = [(data.id+1, data.sell_name) for data in Sell.objects.all()]
sell_id = models.IntegerField(choices=sell_choices,default=1)

请注意,您在定义模型时过滤了对象,因此它只会被评估一次。最好的方法是实现一个过滤对象并将其作为可调用对象放在模型定义中的函数:

# somewhere in your code you define the filtering function
def my_filter():
    return tuple([(data.id+1, data.sell_name) for data in Sell.objects.all()])

# and place the callable in your choices
...
sell_id = models.IntegerField(choices=my_filter,default=1)

【讨论】:

  • 对不起,我已经解释了我的问题
【解决方案2】:

编辑后,你想要的是:

hotel.sell_set.all()  # hotel is an instance of the Hotel model

您可以参考appropriate documentation

Django 还为“另一端”创建 API 访问器 关系——从相关模型到模型的链接 定义关系。例如,博客对象 b 可以访问 a 通过 entry_set 属性列出所有相关的 Entry 对象: b.entry_set.all().

这些是BlogEntry 型号:

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()


class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()

正如我在评论中所说,这回答了您的直接问题,但您将面临其他问题。

【讨论】:

  • 我想在课堂模型中使用,我该怎么做?
  • 我不确定我是否理解,但正如我在评论中所说,动态选择有点复杂。寻找ModelChoiceField
猜你喜欢
  • 1970-01-01
  • 2021-01-20
  • 2017-12-15
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 2018-07-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多