2

私はこのようなものを設定したいくつかのモデルを持っています:

class Bar(models.Model):
  baz = models.CharField()

class Foo(models.Model):
  bar1 = models.ForeignKey(Bar)
  bar2 = models.ForeignKey(Bar)
  bar3 = models.ForeignKey(Bar)

そして、コードの他の場所で、私はBarのインスタンスに行き着き、それが接続されているFooをある程度見つける必要があります。今、私はQを使用して複数のORクエリを実行することを思いつきました。

foo_inst = Foo.objects.get(Q(bar1=bar_inst) | Q(bar2=bar_inst) | Q(bar3=bar_inst))

私が理解する必要があるのは、3つのケースのうち、実際にヒットしたのは、少なくともメンバーの名前(bar1、bar2、またはbar3)です。これを行う良い方法はありますか?その情報を収集するためにクエリを構造化するためのより良い方法はありますか?

4

2 に答える 2

1
try:
    Foo.objects.get(bar1=bar_inst)
    print 'bar1'
except Foo.DoesNotExist:
    try:
        Foo.objects.get(bar2=bar_inst)
        print 'bar2'
    except Foo.DoesNotExist:
        try:
           Foo.objects.get(bar3=bar_inst)
           print 'bar3'
        except Foo.DoesNotExist:
           print 'nothing found'

また、モデルのすべてのバー フィールドにrelated_nameを追加することも検討してください。

于 2012-09-17T08:08:54.430 に答える
0

ChoiceField変更して?を使用できます。

BAR_VERSIONS = (
    ('Bar 1', 'bar1'),
    ('Bar 2', 'bar2'),
    ('Bar 3', 'bar3'),
)


class Bar(models.Model):
  baz = models.CharField()

class Foo(models.Model):
  bar = models.ForeignKey(Bar)
  bar_version = models.ChoiceField(choices=BAR_VERSIONS)

それで:

try:
    foo_instance = Foo.objects.get(bar=bar_instance)
except Foo.DoesNotExist:
    # Handle Exception
    pass
else:
    print(foo_instance.bar_version)

更新: あなたのコメントから、アイデアは何も設定しないか、すべてbarの s を設定することであるため、このアプローチを引き続き使用できますがManyToManyFieldthroughパラメーターで a を使用できます。bar4これにより、try - barnexcept ウォーターフォールを拡張するのではなく、追加したい場合に将来的に拡張可能になります。

https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany

class Bar(models.Model):
  baz = models.CharField()

class Foo(models.Model):
  bars = models.ManyToManyField(bar, through='FooBars')

class FooBars(models.Model):
  foor = models.ForeignKey(Foo)
  bar = models.ForeignKey(Bar)
  bar_version = models.ChoiceField(choices=BAR_VERSIONS)
于 2012-09-17T08:10:39.233 に答える