问题
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