0

I am currently working on a Django project. I am using Foreign Fields in one of the models.

class Purchase (models.Model):
       user = models.ForeignKey(User, blank = True, null = True)
       game = models.ForeignKey(Game)
       ...

And accessing these values in views like

p = Purchase.objects.filter(user=request.user,game=request.POST['gameid'])

In DB(i am using Postgres), the fields in Purchase Table are user_id and game_id respectively for user and game. I think its the Django default to suffix foreign fields with _id.

So i tried a bit in manage.py shell and i came to know that i am getting same amount of results even if i use

 p = Purchase.objects.filter(user_id=request.user,game_id=request.POST['gameid'])

So my doubt is that whether the field names defined in model and exact names of those fields in DB can be used interchangeably? Any further information or explanation would be appreciated. Thanks

4

1 回答 1

0

Django 为外键字段执行此操作。如果您想在数据库中使用相同的名称,则可以使用db_column定义列名:

user = models.ForeignKey(User, db_column='user')

PS您可以同时使用user_iduser来引用外键。这绝对没问题。但我建议您使用模型级别名称以避免混淆。

于 2013-06-24T07:13:56.493 回答