egaoneko
egaoneko

Reputation: 389

Can't find django auth user with PostgreSQL

from django.contrib.auth.models import User as DjangoUser
class Ward(models.Model):
    user = models.ForeignKey(DjangoUser, related_name='wards')
    group = models.ForeignKey(Group, related_name='wards')

This is my django model and I use this filter.

Group.objects.filter(wards__user=_user).all()

I used this code in sqlite3, it works well.

But, it doesn't work in PostgreSQL.

operator does not exist: character varying = integer LINE 1: ...rchive_ward"."group_id" ) WHERE "archive_ward"."user_id" = 1

I think it is caused by user_id field in archive_ward tables. I found this field's data type is character.varying(20).

What can I do for this code?

Upvotes: 0

Views: 703

Answers (2)

Mushahid Khan
Mushahid Khan

Reputation: 2834

Try removing the user table in the database and adding it again.

create a new one from scratch. Syncing database again will work..

or else You can do like this Way raw_query

You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::

Upvotes: 4

Andomar
Andomar

Reputation: 238256

The Postgres error means you're comparing an integer to a string:

operator does not exist: character varying = integer

You could change the database model so user_id is of an integer type. Or you could cast the integer to string in Python:

Group.objects.filter(wards__user=str(_user)).all()

Upvotes: 0

Related Questions