简体   繁体   English

如何为特定用户伪造django.contrib.auth用户值?

[英]How to Fake django.contrib.auth User value for specific user?

I am writing a script and want to fake a User with an id (PK) of 2 我正在编写脚本,并且想要伪造id (PK)为2的用户

var = Table(FKToUser=2)
var.save()

the problem is I'm getting : 问题是我越来越:

"Table.FKToUser" must be a "User" instance

I've verified that the auth_user has a record with id=2 我已验证auth_user的记录具有id=2

How can I fake this 2 value for testing purposes? 如何为测试目的伪造这2值?

Thank you! 谢谢!

Assuming that Table is your model and FKToUser is a foreign key, there are two ways. 假设Table是您的模型,而FKToUser是外键,则有两种方法。 The first is to set the FKToUser_id attribute to 2 and save the model. 第一种是将FKToUser_id属性设置为2并保存模型。 The other is to fetch the user and set the FKToUser attribute to the right user model instance. 另一种是获取用户并将FKToUser属性设置为正确的用户模型实例。

This is also basically how a foreign key works. 基本上,这也是外键的工作方式。 The actual column in the database is the FKToUser_id column, and it's a simple Integer foreign key to an id in another column. 数据库中的实际列是FKToUser_id列,它是另一个列中ID的简单Integer外键。 Django magic makes it possible to automatically retrieve the right instance by accessing FKToUser , and to set the right value by assigning a model instance to FKToUser . Django magic使访问FKToUser可以自动检索正确的实例,并通过将模型实例分配给FKToUser来设置正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM