Reputation: 9
I am a beginner in Django.
I need columns showing only the type_of_due_date that exists in the selected country.
In "class InputType" I tried to use limit_choices_to and Q function, but see a mistake like
int() argument must be a string, a bytes-like object or a number, not 'ForeignKey'#
Please, help. What I did wrong?
My models:
class InputVatDueDate(models.Model):
country = models.ForeignKey(Country, verbose_name='Country', on_delete=models.CASCADE, db_index=True,
blank=True)
date = models.DateField(_('date'), default=datetime.datetime.now)
class Meta:
verbose_name = _('input vat due date')
verbose_name_plural = _('input vats due date')
unique_together = (('country', 'date'),)
def __str__(self):
return self.country.name
class TypeOfVatDueDate(models.Model):
vat_due_date = models.ForeignKey(InputVatDueDate, on_delete=models.CASCADE)
type_of_due_date = models.CharField(max_length=100, choices=enum_to_choice(TypeDueDates))
date_of_start = models.IntegerField(_('day of start date'))
def __str__(self):
return self.type_of_due_date
class InputType(models.Model):
vat_due_company = models.ForeignKey(CompanyVatDueDate, on_delete=models.CASCADE)
country = models.ForeignKey(InputVatDueDate, on_delete=models.CASCADE,)
type_of_due_date = models.ForeignKey(TypeOfVatDueDate, on_delete=models.CASCADE, limit_choices_to=Q(vat_due_date_id=country), )
Upvotes: 0
Views: 137
Reputation: 29967
You problem is here:
class InputType(models.Model):
...
type_of_due_date = models.ForeignKey(TypeOfVatDueDate, on_delete=models.CASCADE, limit_choices_to=Q(vat_due_date_id=country), )
My understanding is that you want to limit the choice to TypeOfVatDueDate
instances where the vat_due_date
is the same value as the country
In this scope, the variable country
is the ForeignKey
field of the model class, not the value of the field country
of the current model instance.
I'm not aware of implement what you are trying to achieve on a model level. You will have to do that at some other place, e.g. in a custom ModelForm:
class InputTypeForm(forms.ModelForm):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
# Restrict queryset if country is set
if self.instance and self.instance.country:
self.fields['type_of_due_date'].queryset = TypeOfVatDueDate.objects.filter(vat_due_date=country)
class Meta:
model = InputType
Upvotes: 1