Django ManyToManyField订购使用 [英] Django ManyToManyField ordering using through
本文介绍了Django ManyToManyField订购使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的模型设置的摘要:
Here is a snippet of how my models are setup:
class Profile(models.Model):
name = models.CharField(max_length=32)
accout = models.ManyToManyField(
'project.Account',
through='project.ProfileAccount'
)
def __unicode__(self)
return self.name
class Accounts(models.Model):
name = models.CharField(max_length=32)
type = models.CharField(max_length=32)
class Meta:
ordering = ('name',)
def __unicode__(self)
return self.name
class ProfileAccounts(models.Model):
profile = models.ForeignKey('project.Profile')
account = models.ForeignKey('project.Accounts')
number = models.PositiveIntegerField()
class Meta:
ordering = ('number',)
然后,当我访问帐户时,如何在中间ProfileAccounts模型中按数字"排序,而不是在帐户模型中按默认的名称"排序?
Then when I access the Accounts, how can I sort by 'number' in the intermediary ProfileAccounts model, rather than the default 'name' in the Accounts Model?:
for acct_number in self.profile.accounts.all():
pass
这行不通,但是是我希望它访问此数据的要点:
This does not work, but is the gist of how I want it to access this data:
for scanline_field in self.scanline_profile.fields.all().order_by('number'):
pass
推荐答案
我刚刚遇到了这个问题.
I just came through this.
class Profile(models.Model):
accounts = models.ManyToManyField('project.Account',
through='project.ProfileAccount')
def get_accounts(self):
return self.accounts.order_by('link_to_profile')
class Account(models.Model):
name = models.CharField(max_length=32)
class ProfileAccount(models.Model):
profile = models.ForeignKey('project.Profile')
account = models.ForeignKey('project.Account', related_name='link_to_profile')
number = models.PositiveIntegerField()
class Meta:
ordering = ('number',)
我删除了除Account.name
之外没有主题的字段.
这是我找到的最短的解决方案,不知道是否可以在2010年使用,但现在肯定可以.
I removed the fields which were off-topic except of Account.name
.
That's the shortest solution I've found, no idea if it was possible to use in 2010, but it certainly is now.
这篇关于Django ManyToManyField订购使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文