Django创建和更新视图:外键字段 [英] Django Create and Update views: foreign key field

查看:331
本文介绍了Django创建和更新视图:外键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两个类:

  class Parcel(models.Model):
name = models .CharField(max_length = NAME_MAX_LENGTH)
garden = models.ForeignKey(Garden,on_delete = models.CASCADE)

def __str __(self):
return self.name

class Bed(models.Model):
宗地=模型.ForeignKey(宗地,on_delete = models.CASCADE)
名称=模型.CharField(max_length = NAME_MAX_LENGTH)
长度= models.IntegerField()
width = models.IntegerField()

我正在使用Django创建和更新新床的通用视图。由于宗地是外键,Django会自动使用数据库中所有现有宗地创建一个select输入。但是,我想告诉Django仅放置具有特定garden_id的包裹。
我查看了函数 get_initial(self),但是我不想为包裹指定初始值,只是缩小包裹的选择范围。 / p>

如果有人有一个主意,对我会有很大帮助。



谢谢。

解决方案

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to



示例:

  staff_member = models.ForeignKey(
User,
on_delete = models.CASCADE,
limit_choices_to = {'is_staff':True},

在您的情况下,可以使用:

  limit_choices_to = {'garden_id__in':['list', 'of','valid','ids']} 

来源:
如何将外键选择仅限于django中的相关对象


Suppose I have the two following classes :

class Parcel(models.Model):
    name = models.CharField(max_length=NAME_MAX_LENGTH)
    garden = models.ForeignKey(Garden, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class Bed(models.Model):
    parcel = models.ForeignKey(Parcel, on_delete=models.CASCADE)
    name = models.CharField(max_length=NAME_MAX_LENGTH)
    length = models.IntegerField()
    width = models.IntegerField()

I'm using Django's generic views to Create and Update new beds. As parcel is a Foreign Key, Django automatically create a select input with all existing parcels in the database. However, I would like to tell Django to put only parcels with a certain garden_id. I looked at the function get_initial(self), but I don't want to specify an initial value for the parcel, just narrow the choices of parcels.

If anyone has an idea, it would help me a lot.

Thank you.

解决方案

https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

Example:

staff_member = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    limit_choices_to={'is_staff': True},
)

In your case maybe use:

limit_choices_to={'garden_id__in': ['list', 'of', 'valid', 'ids']}

Source: How do I restrict foreign keys choices to related objects only in django

这篇关于Django创建和更新视图:外键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆