按SQL排序(Rails Order by SQL)
我有一个TraitQuestion模型,它具有许多特征或答案 - 每个特征或答案都有一个值,例如1,2,3或-3105(对于以上都不是)。 我无法更改这些值,因为它们是外部API所必需的。
我想按价值订购它们,但是当我这样做时,-3105的答案显示在顶部,即使它表示“以上都不是”:
Answer 4 = -3105 Answer 1 = 1 Answer 2 = 2 Answer 3 = 3
关于我们如何订购它的任何想法,以便它
1 2 3 -3105?
我是SQL的新手,但似乎我应该能够做到这样的事情:
@trait_question.traits.order('CASE WHEN value AS int > 0 then 1 ELSE 0 END')
但这不起作用。 任何想法我如何调整顺序调用SQL,以便它将按正确的顺序排序?
编辑:这是通过亚马逊AWS的Postgresql 9.4.1
I have a TraitQuestion model that have a number of traits or answers - each of which has a value such as 1, 2, 3, or -3105 (for none of the above). I can't change these values because they are required for an external API.
I'd like to order them by the value, but when I do that, the answer with -3105 shows up at the top even though it says "None of the above":
Answer 4 = -3105 Answer 1 = 1 Answer 2 = 2 Answer 3 = 3
Any idea on how we could order this so that it's
1 2 3 -3105?
I'm pretty new to SQL but it seems like I should be able to do something like this:
@trait_question.traits.order('CASE WHEN value AS int > 0 then 1 ELSE 0 END')
But that doesn't work. Any ideas how I can adjust the order call SQL such that it would order them in the correct order?
EDIT: This is Postgresql 9.4.1 via Amazon AWS
原文:https://stackoverflow.com/questions/36099163
最满意答案
请更正您的代码
class Playlist(models.Model): name = models.CharField(max_length=200, null=False, blank=False,default='') owner = models.ForeignKey(User, null=True) def __str__(self): return self.name @property def playlist_id(self): return self.id
当您使外键所有者唯一时,这意味着一个用户只能有一个播放列表。 当您尝试为同一用户添加另一个播放列表时,您会收到此错误
UNIQUE约束失败:music_playlist.owner_id
如果您希望一个用户只有一个播放列表,请使用OneToOneField
Please correct your code
class Playlist(models.Model): name = models.CharField(max_length=200, null=False, blank=False,default='') owner = models.ForeignKey(User, null=True) def __str__(self): return self.name @property def playlist_id(self): return self.id
When you make the foreign key owner unique, it means that one user can have only one playlist. When you try to add another playlist for the same user your get this error
UNIQUE constraint failed: music_playlist.owner_id
If you want one user to have only one playlist, use OneToOneField
相关问答
更多-
表格声明的UNIQUE子句指出, player_id , map_id和runID每一行组合必须是唯一的。 你得到这个错误是因为在jumptimes表中已经有一行,其中player_id = 13 , map_id = 34 , runID = 0 。 这里有一个简单的SQLFiddle来重现错误。 错误所谈论的“约束”是UNIQUE子句,如果你能看到完整的错误,那么它与你所得到的错误是一样的。 The UNIQUE clause of your table's declaration states tha ...
-
is_valid()仅验证您在表单中指定的字段(在本例中为 - file )。 表单有效 - 但稍后会出现错误,因为保存时不满足其他模型字段约束。 将owner传递给表单是行不通的,因为表单不处理该字段。 相反,您需要在表单验证后将owner添加到模型中,但在保存之前: if request.method == 'POST': form = DictionaryForm(request.POST, request.FILES) if form.is_valid(): obj ...
-
NOT NULL约束失败:courses_course.owner_id(NOT NULL constraint failed: courses_course.owner_id)[2024-03-20]
如果您尝试打印CourseCreateView的MRO,您会看到: (, , , , , @arne,这是bulk_create的错误方法。 hourlys = [] for i in range(0, 24): hourlys.append(Hourly.objects.create(project=project, clock_time=clock_time)) Hourly.objects.bulk_create(hourlys) 正确的方法是将属性传递给Hourly对象,创建一个列表。 下面是一个压缩版本。 hourlys = [H ...Django UNIQUE约束失败:Site_coach.user_id(Django UNIQUE constraint failed: Site_coach.user_id)[2022-05-25]
您需要传递被修改对象的实例,否则会创建一个新对象,并且保存将失败,因为它是OneToOne : def Register(request): try: coach_instance = coach.objects.get(user=request.user) except coach.DoesNotExist: coach_instance = coach(user=request.user) form = RegisterForm(request.P ...NOT NULL约束失败:device_api_devicegroup.owner_id(NOT NULL constraint failed: device_api_devicegroup.owner_id)[2022-05-10]
仔细看看,用户不在request.data中: serializer = DeviceGroupSerializer(data={ 'name':request.data['name'], 'owner':request.user.id, }) 还要检查序列化程序是否允许使用所有者 from django.contrib.auth.models import User class DeviceGroupSerializer(serializers.ModelSerializer): id ...将关系设置为user = models.OneToOneField(User)意味着每个User只能有一个Change 。 将其更改为: user = models.ForeignKey(User) Setting relation as user = models.OneToOneField(User) means that there can be the only one Change per User. Change it to: user = models.ForeignKey(User)请更正您的代码 class Playlist(models.Model): name = models.CharField(max_length=200, null=False, blank=False,default='') owner = models.ForeignKey(User, null=True) def __str__(self): return self.name @property def playlist_id(self): ...这都是因为在Relation表中你有PRIMARY KEY(ID_SOURCE, ID_DESTINATION)所以这两个值都必须创建唯一的set。 如果您将其更改为PRIMARY KEY(ID_SOURCE, ID_DESTINATION, VALUE) ,那么它应该可以正常工作。 编辑 以下评论中提到的解决方案示例: CREATE TABLE RELATION ( ID INT NOT NULL, ID_SOURCE TEXT NOT NULL, ID_DESTINATION T ...class Product(models.Model): name = models.CharField(max_length=5) vat_rate = models.DecimalField(max_digits=5, decimal_places=2) amount = models.IntegerField(default=0, primary_key=True) 金额设置primary key ,这意味着数据库每个金额值只允许1条记录 。 但是 ,您还设置了default ...相关文章
更多- sql问题
- MyBatis动态参数order by的设置
- MyBatis 动态 SQL详解
- 如何优化这个sql语句
- SQL中GROUP BY与HAVING的用法
- 不会sql语句....谁帮我优化下
- 锋利的SQL
- SQL的一个简单问题
- 一个sql查询
- 关于mysql 的 sql
最新问答
更多- 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
- 如何通过引用返回对象?(How is returning an object by reference possible?)
- 矩阵如何存储在内存中?(How are matrices stored in memory?)
- 每个请求的Java新会话?(Java New Session For Each Request?)
- css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
- 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
- xcode语法颜色编码解释?(xcode syntax color coding explained?)
- 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
- 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
- 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
- 西安哪有PLC可控制编程的培训
- 在Entity Framework中选择基类(Select base class in Entity Framework)
- 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
- 电脑二级VF有什么用
- Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
- 金华英语角.
- 手机软件如何制作
- 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
- 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
- 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
- Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
- 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
- python的访问器方法有哪些
- DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
- 在Ruby中对组合进行排序(Sorting a combination in Ruby)
- 网站开发的流程?
- 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
- 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
- 透明度错误IE11(Transparency bug IE11)
- linux的基本操作命令。。。