Django: how to change the parameters of an external filter key by setting Django_Admin

I have three models: LineType, Service, DomainName, Record, they are related m2m or foreignkey to each other. here is the code:

class LineType(models.Model): linename = models.CharField(max_length=30,primary_key=True) def __unicode__(self): return self.linename class Service(models.Model): servicename = models.CharField(max_length=30,primary_key=True) price = models.DecimalField(max_digits=8, decimal_places=2) line = models.ManyToManyField(LineType) def __unicode__(self): return self.servicename class DomainName(models.Model): domainname = models.CharField(max_length=30,primary_key=True) user = models.ForeignKey(SiteProfile) service = models.ForeignKey(Service) def __str__(self): return self.domainname class Record(models.Model): TYPE_CHOICES = ( ('A','A'), ('CNAME','CNAME'), ('MX','MX'), ) domainname = models.ForeignKey(DomainName) def get_line(self): domain = DomainName.objects.get(pk=self.domainname_id) service = Service.objects.get(pk=domain.service_id) lines = service.line.all() choices = [] for x in lines: choices.append((x.linename,x.linename)) return choices host = models.CharField(max_length=30) type = models.CharField(max_length=5,choices=TYPE_CHOICES,default='A') line = models.ForeignKey(LineType) destaddress = models.CharField(max_length=30) 

Let me introduce a model. Each domain name can have only one Service that other DomainNames can have. Each domain name has several entries. The service defines LineTypes that can be applied to the record.

I use Django admin to manage these models, but selecting the β€œrow” in the record is all LineType objects. So the question is how to filter the LineType entries according to the β€œservice” of this parent (DomainName).

+4
source share
1 answer

Depending on your exact requirement and your version of Django, the answer can either set the limit_choices_to attribute of the foreign key , or configure the ModelAdmin form:

Using limit_choices_to

Just limit the selection of strings to those matching linename == 'foo'

 class Record(models.Model): # ... line = models.ForeignKey(LineType, limit_choices_to={'linename': 'foo'})) 

Using custom form

If an instance exists with an instance, we can select it as a set of query options

 class RecordAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(RecordAdminForm, self).__init__(*args, **kwargs) # access object through self.instance... if self.instance: valid_lines = self.instance.domainname.service.line.objects.all() self.fields['line'].queryset = valid_lines class RecordAdmin(admin.ModelAdmin): form = RecordAdminForm # ... 

Reference SO questions:

0
source

Source: https://habr.com/ru/post/1442331/


All Articles