Save a foreign key in postgreSQL using python-django


I’m trying to a save a foreign key inside an object into my db using a form, but i get the error : ‘Syntax isn’t valid for integer’, I discovered that postgreSQL save the foreign key as an id, how can i save it then?

Here it is my code. :

class treballador(models.Model):
    nom = models.CharField(max_length=150, null=False, unique=True)
    cognom = models.CharField(max_length=150, null=False)
    tipusDocID = models.CharField(max_length=3, choices=TIPUSDOC, null=False)
    docId = models.CharField(max_length=9, null=False)
    tlf_regex = RegexValidator(regex=r'^\d{9,9}$',message="Phone number must be entered in the format: '+999999999'. Up to 9 digits allowed.")
    tlf = models.CharField(validators=[tlf_regex], blank=True, max_length=9)  # validators should be a list
    correu = models.EmailField(max_length=254)
    ciutat = models.CharField(max_length=150)
    dataDAlta = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return unicode(self.nom) or unicode(

class despesa(models.Model):
    nomTreballador = models.ForeignKey(treballador, to_field='nom')
    tipusDeGast = models.CharField(max_length=3, choices=GASTOS)
    quantia = models.DecimalField(max_digits=5, decimal_places=2)
    data = models.DateTimeField()

class desModelForm(forms.ModelForm):
    data = forms.DateField(widget=DateInput(format='%d/%m/%Y'), label="Data de la despesa", input_formats=['%d/%m/%Y'])

    class Meta:
        model= despesa
        fields= ["nomTreballador","tipusDeGast","quantia","data"]

        def clean_despesa(self):
            despeses = self.cleaned_data.get("tipusDeGast")
            return despeses

        def clean_date(self):
            date = self.cleaned_data.get("data")
            return date

        def clean_quantia(self):
            quantia = self.cleaned_data.get("quantia")
            return quantia

        def clean_nom(self):
            nomTreballador = self.cleaned_data.get("nomTreballador")
            return nomTreballador

    def __init__(self, *args, **kwargs):
        super(desModelForm, self).__init__(*args, **kwargs)

def home(request):
    form = desModelForm(request.POST or None)

    context = {
        "gast_form": form

    if form.is_valid():

        desp =

    return render(request, "imputacioDespeses.html", context)


Remove to_field='nom' from the nomTreballador ForeignKey field and it will insert the Treballador‘s primary key (an integer) instead of nom (which is a string).

Answered By – voodoo-burger

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published