开发者

How can i order queryresults by the PK of a m2m-relationtable?

开发者 https://www.devze.com 2023-02-14 02:16 出处:网络
I have a model with a m2m relation to users: class SomeModel(models.Model): user=models.ManyToManyField(User,related_name=\'linked\',blank=True,null=True)

I have a model with a m2m relation to users:

class SomeModel(models.Model):
    user=models.ManyToManyField(User,related_name='linked',blank=True,null=True)  

to which i have a query:

lin开发者_运维问答ked_objects=SomeModel.objects.filter(user__id__contains=request.user.id)  

The results are the ordered by the user id. What i want to do, is to sort the results by the primary key of the relation table between User and SomeModel, which would be appname_somemodel_user. Is this possible?


Might be wrong about this, but I think you can only refer to the intermediary table if you specify it yourself explicitly.

class SomeModel(models.Model):
    user=models.ManyToManyField(User,related_name='linked',blank=True,null=True, through='SomeModelUser')

class SomeModelUser(models.Model):
    user = models.ForeignKey(User)
    some_model = models.ForeignKey(SomeModel)

linked_objects=SomeModel.objects.filter(user__id__contains=request.user.id).order_by('somemodeluser__pk')
0

精彩评论

暂无评论...
验证码 换一张
取 消