Let's say I have two tables: customer
and city
. I have customer.city_id
field as a foreign key that references city.id
.
假设我有两个表:客户和城市。我有customer.city_id字段作为引用city.id的外键。
class Customer(model.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=50)
city_id = models.ForeignKey(City, models.DO_NOTHING, db_column='id'
class Meta:
managed = False
db_table = 'customer'
def __str__(self):
return self.name
class City(model.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=32)
added = models.PositiveIntegerField() # value is 1 or 0
class Meta:
managed = False
db_table = 'city'
def __str__(self):
return self.name
When I add a new customer, I can pull all the records (city names) and display them in the add new customer page. How can I get only the cities that their city.added
value = 1
and ignore those with value 0
, Preferably in the models.py
file or in the admin.py
file.
当我添加新客户时,我可以提取所有记录(城市名称)并在添加新客户页面中显示它们。如何只获取其city.added值= 1的城市,并忽略值为0的城市,最好是在models.py文件或admin.py文件中。
1 个解决方案
#1
0
I got it sorted out with the get_form function. This is how I did it (in the CustomerAdmin
class):
我用get_form函数整理了它。我就是这样做的(在CustomerAdmin类中):
def get_form(self, request, obj=None, **kwargs):
form = super(CustomerAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['city_id'].queryset = City.objects.filter(added=1)
return form
It's amazing how easy it is to miss things in front of us when working for more than 30 hours continuously!
令人惊讶的是,在连续工作超过30小时的时候,错过我们面前的事情是多么容易!
#1
0
I got it sorted out with the get_form function. This is how I did it (in the CustomerAdmin
class):
我用get_form函数整理了它。我就是这样做的(在CustomerAdmin类中):
def get_form(self, request, obj=None, **kwargs):
form = super(CustomerAdmin, self).get_form(request, obj, **kwargs)
form.base_fields['city_id'].queryset = City.objects.filter(added=1)
return form
It's amazing how easy it is to miss things in front of us when working for more than 30 hours continuously!
令人惊讶的是,在连续工作超过30小时的时候,错过我们面前的事情是多么容易!