首页 \ 问答 \ Django,自定义管理器会影响保存方法吗?(Django, Custom Managers affect save method?)

Django,自定义管理器会影响保存方法吗?(Django, Custom Managers affect save method?)

我正在使用Django 1.7。 我有一个默认的自定义管理器,可以过滤“活动”布尔字段。 根据文档,它需要是使用相关字段的默认管理器(即访问User.story_set仅显示活动的Story对象)。 我保留了管理员和shell访问的标准管理器,但我无法保存对象的更改,我猜测因为save()方法在某些时候通过默认管理器。

class Story(models.Model):
    active = models.BooleanField(default=True)
    ....

    objects = ActiveStoryManager()
    full_set = models.Manager()

class ActiveStoryManager(models.Manager):
    def get_query_set(self):
        return super(ActiveStoryManager, self).get_query_set().filter(active=True)
    use_for_related_fields = True

这适用于所有面向公众的用途。 但是,在admin和shell中,我无法影响非活动对象,包括将它们恢复为活动状态。

story = Story.full_set.get(id=#)将获取一个active=False的故事,但在设置active=True我无法保存,得到一个

django.db.utils.IntegrityError: duplicate key value violates unique constraint "stories_story_pkey" DETAIL: Key (id)=(#) already exists.

调用save.(force_update=True)返回django.db.utils.DatabaseError: Forced update did not affect any rows.

因此,虽然save()是一个模型方法,但它似乎依赖于保存过程中某个时刻的默认管理器。

解决方法是使用Queryset API,例如Story.full_set.filter(id=#).update(active=True) ,但这只能在shell中使用,并且需要手动键入每个更改,仍然无法保存非活动实例管理员。

对此有何帮助?


I'm using Django 1.7. I've got a default custom manager that filters on an "active" boolean field. According to the docs, it needs to be the default manager to work with related fields (ie. accessing User.story_set only shows active Story objects). I'm keeping the standard manager for admin and shell access, but I am unable to save changes to objects, I'm speculating because save() methods pass through the default manager at some point.

class Story(models.Model):
    active = models.BooleanField(default=True)
    ....

    objects = ActiveStoryManager()
    full_set = models.Manager()

class ActiveStoryManager(models.Manager):
    def get_query_set(self):
        return super(ActiveStoryManager, self).get_query_set().filter(active=True)
    use_for_related_fields = True

This works well for all public-facing use. However, in admin and shell I am unable to affect inactive objects, including turning them back active.

story = Story.full_set.get(id=#) will fetch a story with active=False, but after setting active=True I am unable to save, getting a

django.db.utils.IntegrityError: duplicate key value violates unique constraint "stories_story_pkey" DETAIL: Key (id)=(#) already exists.

Calling save.(force_update=True) returns django.db.utils.DatabaseError: Forced update did not affect any rows.

So while save() is a model method, it seems to depend on the default manager at some point in the saving process.

A workaround is using the Queryset API, e.g. Story.full_set.filter(id=#).update(active=True), but that's only usable in the shell, and requires manually typing each change, still can't save inactive instances in the admin.

Any help on this?


原文:https://stackoverflow.com/questions/27085886
更新时间:2022-03-24 07:03

最满意答案

是。 如果已经发出信号,则不会有任何等待。 没关系。

实际上,如果你查看WaitOne(int)的返回值,你会看到它已经设置(或者在超时之前设置WaitOne(int)它返回true ,如果它没有在你的超时值中设置,则返回false

这种区别有时很重要,因此要注意有回报值。


Yes. If it's already signalled, there won't be any waiting done. That's fine.

In fact, if you look at the return value of WaitOne(int) you'll see that it returns true if it is already set (or gets set before the timeout), and false if it doesn't get set within your timeout value.

That distinction is sometimes important so be aware that there is a return value.

相关问答

更多
  • 是。 如果已经发出信号,则不会有任何等待。 没关系。 实际上,如果你查看WaitOne(int)的返回值,你会看到它已经设置(或者在超时之前设置WaitOne(int)它返回true ,如果它没有在你的超时值中设置,则返回false 。 这种区别有时很重要,因此要注意有回报值。 Yes. If it's already signalled, there won't be any waiting done. That's fine. In fact, if you look at the return val ...
  • 我试图加强安全配置时遇到了这个问题。 就你而言,我能够从所有mongos实例连接到配置服务器。 在我的情况下,我也在测试一个副本集的成员处于不同的数据中心的情况,并且只有在执行一些初始化之后才有问题。 最后我注意到,并不是假装的错误信息,问题发生在一个数据中心的一些初级设备上,他们无法返回到配置服务器。 在修复路由问题(最终/ etc / hosts)之后,mongo方面没有发生更多的问题。 I just ran into this problem while trying to harden the se ...
  • 一个好的方法是在事件处理程序中使用NO代码(除了方法/函数调用)。 这可以在程序中的任何地方调用它。 A good way would be to have NO code (except a method/function call) in an event handler. this would made it possible to call it from any place in your program.
  • Windows不维护每线程事件状态。 事件是否发出信号,所有线程都将看到相同的状态。 如果有两个线程正在等待一个事件,并且两个线程在发出信号后重置该事件,则存在一个线程根本看不到信号的风险(因为另一个线程已经重置了它)。 您需要一个同步机制,以便只有在检查它的所有线程都看到新状态时才会重置事件(例如,每个线程递减的原子计数器,并且只有当事件达到0时才会重置事件)。 根据您的应用,信号量可能更合适。 Windows doesn't maintain per-thread event states. An ev ...
  • 从数据库中检索记录时计算计算字段,因此在数据集上调用Refresh (或Close - > Open)以强制重新计算。 (关于对问题的评论),要强制仅对一条记录进行重新计算,可以在数据集上调用RefreshRecord 。 如果特定数据集后代未实现该方法,则Edit后跟Cancel调用将实现相同。 Calculated fields are calculated when records are retrieved from the database, so call Refresh (or Close - ...
  • 而不是ObjectId() ,您可能需要使用Meteor.Collection.ObjectID() 。 有关更多详细信息,请参阅Meteor.Collection.ObjectID()与MongoDB ObjectId() 。 I was able to figure it out. I needed to set it in the following way: var original_id = new Meteor.Collection.ObjectID().valueOf();
  • 如果您希望两个线程都对hTerminateEvent做出反应,则必须将其设置为手动重置。 据推测,您正在使用它作为告诉多个线程自行终止的信号,因此无论如何将它设置为自动重置是没有意义的。 与hStateChangedEvent相同。 如果您阅读CreateEvent()文档,它会说: bManualReset [in] 如果此参数为TRUE,则该函数将创建手动重置事件对象,该对象需要使用ResetEvent函数将事件状态设置为无信号。 如果此参数为FALSE,则该函数将创建自动重置事件对象,并且系统会在释放 ...
  • 它阻止了主线程。 这是唯一可以阻止的。 你不能强迫另一个线程睡觉。 主线程将等待另一个线程“设置”该事件。 这非常像Monitor.Wait / Pulse 。 It blocks the main thread. That's the only one it can block. You can't force another thread to sleep. The main thread will wait for the other thread to "set" the event. This i ...
  • 尝试WaitHandle.WaitAny并包含CancellationToken.WaitHandle 。 可在此处找到可取消的WaitAll的讨论 Try WaitHandle.WaitAny and include the CancellationToken.WaitHandle. A discussion of a cancellable WaitAll can be found here
  • 没有记录的方法可以做到这一点,但如果你冒险进入无证土地,实际上并不难。 (为了您的目的,这应该没问题,因为它不会真正影响您的程序的功能。) 你需要做的第一件事是弄清楚给你的句柄是否是一个事件。 你使用NtQueryObject。 该功能记录在此处: http : //msdn.microsoft.com/en-us/library/bb432383(v = vs.85).aspx 。 它附带了本机API的通常附带条款,它可能会在没有通知的情况下消失或更改。 部分示例: #include

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)