- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在处理数据库模型的实例,我需要从内存中的数据构造对象(使用 Python 风格的 o = Object()
而不是 ModelClass.objects .create()
。是否将数据保存在数据库中将在稍后调用 o.save()
时决定。
这些模型有一个 ManyToManyField
并拥有许多子对象。问题是,在实际保存子对象之前,我无法将 add()
添加到 ManyToManyField
中。我怎样才能以以后可以调用 save()
的方式构造这些对象?我发现的这个问题的每一个潜在解决方案实际上都没有达到我想要的效果。
下面是一些示例代码,展示了我正在尝试做的事情:
class Author:
# ...
@classmethod
def create(cls, data):
# ...
pass
class Book(models.Model):
title = models.CharField(max_length=128)
pages = models.PositiveIntegerField()
authors = models.ManyToManyField(Author)
@classmethod
@transaction.atomic
def create(cls, data):
try:
with transaction.atomic():
b = cls(title=data["title"],
pages=data["pages"])
# This works, but has an unwanted side effect: authors are saved to the database
# as they're created here while the Book is not saved.
b.authors = Author.objects.bulk_create([Author.create(a) for a in data["authors"]])
return b
except Exception:
# ...
raise
################### Later on...
# This data is NOT static - it's formed from JSON which comes from an API. Just is here as an example.
data = {
"title": 1,
"pages": 934,
"authors": [
{
"name": "John Smith",
# ...
}
]
}
# We're going to use this now, but we're unsure if we want to actually save
# the object to the database.
b = Book.create(data)
# Save the data to the database if we want to.
b.save()
最佳答案
我能想到的唯一解决方案是将操作排队并在您调用 save()
时执行它们。
class PostponedOpMixin(models.Model):
def __init__(self, *args, **kwargs):
self._postponed_ops = []
super(PostponedOpMixin, self).__init__(*args, **kwargs)
def _getattr(self, attr):
result = self
for part in attr.split('.'):
result = getattr(result, part)
return result
def postpone(self, op, *args, **kwargs):
if self.pk: # execute now if self already has a pk
return self._getattr(op)(*args, **kwargs)
self._postponed_ops.append((op, *args, **kwargs))
def save(self, *args, *kwargs):
super(PostponedOpMixin, self).save(*args, **kwargs)
while self._postponed_ops:
op, args, kwargs = self._postponed_ops.pop(0):
self._getattr(op)(*args, **kwargs)
def Meta:
abstract = True
这样你就可以做到:
class Book(PostponedOpMixin):
...
authors = models.ManyToManyField(Author)
...
instance = Book()
instance.title = "Romeo and Juliet"
instance.postpone('authors.add', shakespeare)
...
# and some time later:
instance.save()
此代码未经测试,旨在作为起点。任何错误都留给读者作为练习。
关于python - 从内存中的数据初始化属于 ManyToManyField 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27550458/
如果有一张有客户的 table 和一张有地址的 table 。 一位客户必须(仅)有一个地址,但地址不必有客户(取决于字段类型)。所以我只是问如何告诉cake在寻找客户时获取客户地址,但在寻找地址时不
我有一个问题,我需要获取我的画廊表的所有图像(路径),该表拥有博物馆和拥有博物馆的用户。我得到了图像的路径,但这些与拥有博物馆的 user_id 没有关联。 所以简短的描述: 每个用户拥有一个博物馆,
我有一个问题,我需要获取我的画廊表的所有图像(路径),该表拥有博物馆和拥有博物馆的用户。我得到了图像的路径,但这些与拥有博物馆的 user_id 没有关联。 所以简短的描述: 每个用户拥有一个博物馆,
我有用户和个人资料(一对一属于用户) type User struct { ID int Username string Password string
我想以类似于'belongs to' association的方式使用GORM的Django's one-to-one relationships。考虑以下示例,其中每个User与一个Profile相
长期从事 Rails 开发, Backbone 菜鸟。 在我的 Rails 模型中,一个项目有很多任务,一个任务属于一个项目......标准的东西。 尝试在集合中获取项目的任务 json。 Examp
让我们直奔问题(使用 Grails 1.1.1,它应该适用于以前的问题) 我有 2 个域,即:用户和详细信息,如下所示: Class User { String userName ; ..
我正在尝试在 Rails 中设置模型关系,并且需要您的帮助,因为它不起作用:0 class User :creator_id end 就架构而言,request_threads表具有creator_
注意:我在编写问题时解决了问题,因此不需要答案。仍然与答案分享,以便有相同经历的人可以从中受益。 我有一个回收器 View ,其中包含图像和 2 个 TextView 。我想在单击图像时旋转图像,但发
我正在尝试为我的应用程序中的所有按钮添加自定义点击声音。我已经为 UIButton 创建了一个类类别,其中包含以下代码: NSURL *soundURL = [NSURL fileURLWithPat
我有这样一个IP:12.12.12.12 我正在遍历不同的 IP 范围(12.12.12.0/24(示例))格式,并尝试查看 IP 是否在该范围内。 我尝试了各种方法,例如 inet_addr 和比较
看完这个问题 ASP.NET MVC: Nesting ViewModels within each other, antipattern or no? 和 Derick Bailey 的评论 i t
我正在使用 FeedWordPress 从子公司网页将新闻导入母公司的新闻卷。 可在此处查看特定项目的 RSS 摘录:Pastebin 如您所见,我正在将我需要的图像放入 RSS 文件、描述 bloc
假设我有以下数据库架构: dogs 和 owners 与经典的 belongsToMany 相关联。 walks 表怎么样?我希望能够在这种关系中使用 Eloquent 好东西: $dogs = Do
我不知道出了什么问题,但我无法使用 :class_name 选项让belongs_to 工作。有人可以启发我。非常感谢! 这是我的代码片段。 class CreateUsers false
属于 JavaScript 对象原型(prototype)的回调函数如何访问对象成员?回调不能关闭,一切都必须定义如下: function Obji(param){ this.element =
有人可以解释一下 MarkupCompilePass1 和 PartialClassGenerationTask 这两个构建任务是如何归属在一起的吗?目前我不知道他们是否共存或者是否需要对方。有人可以
现在,我尝试了解 Grails 域类和 GORM 中的工作原理。所以,我尝试实验: 我试验了两个域类:Main 和 Sub。 我们走吧! 第 1 步: class Main { String
所以我有一个模型 App.DailyEntry = DS.Model.extend({ user_id: belongsTo('user'), entries: hasMany('En
我正在使用 primeng 组件选项卡菜单。 https://www.primefaces.org/primeng/#/tabmenu我找不到将所选 TAB 的颜色更改为不同颜色的方法。 最佳答案 抱
我是一名优秀的程序员,十分优秀!