首页 \ 问答 \ Django Admin ManyToMany错误(Django Admin ManyToMany error)

Django Admin ManyToMany错误(Django Admin ManyToMany error)

我正在使用内置的django管理站点来保存具有ManyToMany字段的模型的实例。 如果我保存而不是更新管理站点中的模型而没有为ManyToMany字段设置值,则可以保存。 保存模型后,我也可以返回并设置ManyToMany字段。 但是,如果我尝试保存我的模型的新实例,运动,具有ManyToMany字段,Exercise.muscles,设置我得到以下错误:

(1452,'无法添加或更新子行:外键约束失败( vitality projectvitality_exercise_muscles ,CONSTRAINT exercise_id_refs_exercise_id_a5d4ddd6 FOREIGN KEY( exercise_id )REFERENCES projectvitality_exerciseexercise_id ))')

我的mysql表设置为INNODB。

我的模型如下:

class Muscle(models.Model):
    def format(self):
            return "name:{0}:".format(self.name)

    def __unicode__(self):
            return unicode(self.name)

    muscle_id = UUIDField(primary_key = True)
    name = models.CharField(max_length=30, blank=False, default="")
    medical = models.CharField(max_length=150, blank=True, default="")
    description = models.TextField(blank=True, default="")

class Exercise(models.Model):
    def format(self):
            return "name:{0}".format(self.name)

    def __unicode__(self):
            return unicode(self.name)

    ISOLATION_TYPE = "isolation"
    COMPOUND_TYPE = "compound"
    FULL_BODY_TYPE = "full"

    EXERCISE_TYPES = (
            (ISOLATION_TYPE, "Isolation"),
            (COMPOUND_TYPE, "Compound"),
            (FULL_BODY_TYPE, "Full Body")
    )

    UPPER_BODY_GROUP = "upper"
    LOWER_BODY_GROUP = "lower"

    GROUP_CHOICES = (
            (UPPER_BODY_GROUP, "Upper Body"),
            (LOWER_BODY_GROUP, "Lower Body")
    )

    exercise_id = UUIDField(primary_key=True)
    name = models.CharField(max_length=30, default="", blank=False)
    description = models.TextField(blank=True, default="")
    group = models.CharField(max_length=255,
            choices=GROUP_CHOICES,
            blank=False,
            default=UPPER_BODY_GROUP)
    exercise_type = models.CharField(max_length=255,
            choices=EXERCISE_TYPES,
            blank=False,
            default=ISOLATION_TYPE)
    muscles = models.ManyToManyField('Muscle', blank=True, null=True)

    class Meta:
            verbose_name = "Exercise"
            verbose_name_plural = "Exercises"

I'm using the the built in django admin site to save instances of a model that has a ManyToMany field. If I save, not update, a model in the admin site without setting a value for the ManyToMany field it saves fine. I can also come back and set the ManyToMany field after saving the model and that works. However, if I try to save a new instance of my model, Exercise, that has the ManyToMany field, Exercise.muscles, set I get the following error:

(1452, 'Cannot add or update a child row: a foreign key constraint fails (vitality.projectvitality_exercise_muscles, CONSTRAINT exercise_id_refs_exercise_id_a5d4ddd6 FOREIGN KEY (exercise_id) REFERENCES projectvitality_exercise (exercise_id))')

My mysql tables are set to INNODB.

My models are as follows:

class Muscle(models.Model):
    def format(self):
            return "name:{0}:".format(self.name)

    def __unicode__(self):
            return unicode(self.name)

    muscle_id = UUIDField(primary_key = True)
    name = models.CharField(max_length=30, blank=False, default="")
    medical = models.CharField(max_length=150, blank=True, default="")
    description = models.TextField(blank=True, default="")

class Exercise(models.Model):
    def format(self):
            return "name:{0}".format(self.name)

    def __unicode__(self):
            return unicode(self.name)

    ISOLATION_TYPE = "isolation"
    COMPOUND_TYPE = "compound"
    FULL_BODY_TYPE = "full"

    EXERCISE_TYPES = (
            (ISOLATION_TYPE, "Isolation"),
            (COMPOUND_TYPE, "Compound"),
            (FULL_BODY_TYPE, "Full Body")
    )

    UPPER_BODY_GROUP = "upper"
    LOWER_BODY_GROUP = "lower"

    GROUP_CHOICES = (
            (UPPER_BODY_GROUP, "Upper Body"),
            (LOWER_BODY_GROUP, "Lower Body")
    )

    exercise_id = UUIDField(primary_key=True)
    name = models.CharField(max_length=30, default="", blank=False)
    description = models.TextField(blank=True, default="")
    group = models.CharField(max_length=255,
            choices=GROUP_CHOICES,
            blank=False,
            default=UPPER_BODY_GROUP)
    exercise_type = models.CharField(max_length=255,
            choices=EXERCISE_TYPES,
            blank=False,
            default=ISOLATION_TYPE)
    muscles = models.ManyToManyField('Muscle', blank=True, null=True)

    class Meta:
            verbose_name = "Exercise"
            verbose_name_plural = "Exercises"

原文:https://stackoverflow.com/questions/16887064
更新时间:2023-08-07 19:08

最满意答案

假设您的MultiRNNCell中有3个RNNCell,并且每个都是具有LSTMStateTuple状态的LSTMCell。 您必须使用占位符复制此结构:

lstm0_c = tf.placeholder(...)
lstm0_h = tf.placeholder(...)
lstm1_c = tf.placeholder(...)
lstm1_h = tf.placeholder(...)
lstm2_c = tf.placeholder(...)
lstm2_h = tf.placeholder(...)

initial_state = tuple(
  tf.nn.rnn_cell.LSTMStateTuple(lstm0_c, lstm0_h),
  tf.nn.rnn_cell.LSTMStateTuple(lstm1_c, lstm1_h),
  tf.nn.rnn_cell.LSTMStateTuple(lstm2_c, lstm2_h))

...

sess.run(..., feed_dict={
  lstm0_c: final_state[0].c,
  lstm0_h: final_state[0].h,
  lstm1_c: final_state[1].c,
  lstm1_h: final_state[1].h,
  ...
})

如果您有N个堆叠的LSTM图层,则可以使用for循环以编程方式创建占位符和feed_dict。


Suppose you have 3 RNNCells in your MultiRNNCell and each is a LSTMCell with an LSTMStateTuple state. You must replicate this structure with placeholders:

lstm0_c = tf.placeholder(...)
lstm0_h = tf.placeholder(...)
lstm1_c = tf.placeholder(...)
lstm1_h = tf.placeholder(...)
lstm2_c = tf.placeholder(...)
lstm2_h = tf.placeholder(...)

initial_state = tuple(
  tf.nn.rnn_cell.LSTMStateTuple(lstm0_c, lstm0_h),
  tf.nn.rnn_cell.LSTMStateTuple(lstm1_c, lstm1_h),
  tf.nn.rnn_cell.LSTMStateTuple(lstm2_c, lstm2_h))

...

sess.run(..., feed_dict={
  lstm0_c: final_state[0].c,
  lstm0_h: final_state[0].h,
  lstm1_c: final_state[1].c,
  lstm1_h: final_state[1].h,
  ...
})

If you have N stacked LSTM layers you can programmatically create the placeholders and feed_dict with for loops.

相关问答

更多
  • 假设您的MultiRNNCell中有3个RNNCell,并且每个都是具有LSTMStateTuple状态的LSTMCell。 您必须使用占位符复制此结构: lstm0_c = tf.placeholder(...) lstm0_h = tf.placeholder(...) lstm1_c = tf.placeholder(...) lstm1_h = tf.placeholder(...) lstm2_c = tf.placeholder(...) lstm2_h = tf.placeholder(... ...
  • 通常,除非您将其分配给tf.Variable或将其 排入队列 ,否则TensorFlow将丢弃在不再需要时立即计算Session.run()结果时使用的所有中间张量的值,以释放记忆力。 此规则的一个例外是,如果在程序中z是常量张量,并且Node1()是无状态操作(即纯函数 ),则TensorFlow可以将Node1()的结果缓存为常量折叠优化的一部分。 此优化可以使Session.run()后续执行更快,但代价是第一次运行时的一些额外工作。 但是,如果z是变量,或者Node1()是有状态操作,则Tensor ...
  • TL; DR:在初始化变量之后,在尝试评估input_batch之前尝试添加以下行: tf.train.start_queue_runners(sess) 如果没有看到inputs()的实现,很难确定,但是张量名称"input/shuffle_batch"表明该函数正在使用tf.train.shuffle_batch()函数构建输入。 许多用于输入处理的TensorFlow函数在内部创建预取队列,包括tf.train.shuffle_batch() 。 这些预取队列最初为空,并且您的sess.run(in ...
  • 您需要将字符编码为int值 U 0 R 1 L 2 D 3 你的输入应该是: [[0,1,2,3,2,2,3,1],[0,1,2,1,2,1,3,1]...] 并添加一个嵌入层(使用tf.contrib.layers.embed_sequence嵌入输入数据)并将编码数据提供给您的lstm单元格。 You need to encode the character to int values U 0 R 1 L 2 D 3 your input should be: [[0,1,2,3,2,2,3,1] ...
  • 经过几个小时的搜索,我自己找到了解决方案。 所以,我现在回答我自己的问题。 队列由后台线程填充,后台线程在调用tf.train.start_queue_runners()时创建。如果不调用此方法,后台线程将无法启动,队列将保持为空,并且训练操作将无限期阻塞等待输入。 FIX:在训练循环之前调用tf.train.start_queue_runners(sess) 。 就像我在下面做的: queue=tf.FIFOQueue(capacity=50,dtypes=[tf.float32,tf.float32], ...
  • 好问题。 首先, feed_dict只是一个python 字典 ,其中每个键都是一个tf.placeholder ,每个对应的值都是一个python对象。 此对象的形状必须等于相应占位符的形状,并且必须具有可以强制插入占位符dtype的数据类型。 feed_dict的结构由图的结构决定,因为图中的每个占位符必须有一个字典键值元组。 要获取图表中的所有占位符,以下单行将执行: placeholders = [ op for op in graph.get_operations() if op.type == ...
  • 得到它修复。 cudnn版本与tensorflow版本不匹配 - 它仅将错误输出提供给python控制台,而不是jupyter笔记本 Got it fixed. The cudnn version mismatched the tensorflow version - it gave the error output only to python console, not to the jupyter notebook
  • 完全连接层是将输入张量转换为输出张量的数学运算。 输出张量包含图层激活函数返回的值,该图层根据图层输入张量中加权值的和进行操作。 当您执行sess.run(fc_3) ,TensorFlow将执行三个层的转换,并为您提供第三层生成的输出张量。 A fully-connected layer is a math operation that transforms an input tensor into an output tensor. The output tensor contains the valu ...
  • 默认情况下,tensorflow会话会占用所有GPU内存。 您可以在创建会话时覆盖默认值。 从这个答案 : gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) 也就是说,创建图表/创建会话比仅对会话进行推理要昂贵得多,因此您不希望为每个单独的查询图像执行此操作。 你可能会更适合运行一个服务器来构 ...
  • 通过调用model_method.build()函数,您可以创建一个计算图。 在这个调用中,每行代码都被执行(因此为什么pdb停止)。 然而, tf.Session.run(...)只执行那些计算提取值所需的计算图的部分(在你的例子中self.op_A , self.op_B )。 该函数不会再次执行整个build()函数。 因此,当您运行sess.run(...)时, pdb.set_trace()没有执行的原因是因为它们不是有效的Tensor对象,因此也不是计算图的一部分。 UPDATE 考虑以下: c ...

相关文章

更多

最新问答

更多
  • 您如何使用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)