如何使用ForeignKey获取模型字段

时间:2015-09-04 14:16:34

标签: python django django-models

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

想要结果[<sell:banana>,<sell:apple>]

我尝试Sell.objects.all() 得到[<sell:banana>,<sell:apple>,<sell:grapes>,<sell:starfruit>] 这不是我想要的结果

2 个答案:

答案 0 :(得分:0)

我没有得到你想做的事。你能更好地解释一下吗? 不是这样的吗?

# 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)

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

std::unique_ptr

答案 1 :(得分:0)

编辑后,你想要的是:

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

您可以参考appropriate documentation

  

Django还为“其他”方创建了API访问器   relationship - 从相关模型到模型的链接   定义了这种关系。例如,Blog对象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()

正如我在评论中所说,这可以回答你的直接问题,但你会遇到其他问题。

相关问题