Django Create and Update views: foreign key field

天大地大妈咪最大 提交于 2019-12-11 05:11:37

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/50580882/django-create-and-update-views-foreign-key-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!