55

申し訳ありませんが、私は Django と Python をまったく初めて使用します。

2 つの質問があります。まず、オブジェクトのリストで最後に作成されたオブジェクト (または最高の pk) を取得するにはどうすればよいですか? たとえば、次のようにして最初のオブジェクトを取得できることがわかっています。

list = List.objects.all()[0]

List.objects の長さを取得する方法はありますか? List.objects.length を試しましたが、役に立ちませんでした。

次に、フィルターを同時に作成したり、リストを組み合わせたりすることはできますか? 次に例を示します。

def findNumber(request, number)
    phone_list = Numbers.objects.filter(cell=number)

上記のようなものが欲しいのですが、もっと似ています:

def findNumber(request, number)
    phone_list = Numbers.objects.filter(cell=number or home_phone=number)

もしあれば、正しい構文は何ですか?

4

8 に答える 8

78

I haven't tried this yet, but I'd look at the latest() operator on QuerySets:

latest(field_name=None)

Returns the latest object in the table, by date, using the field_name provided as the date field.

This example returns the latest Entry in the table, according to the pub_date field:

Entry.objects.latest('pub_date')

If your model's Meta specifies get_latest_by, you can leave off the field_name argument to latest(). Django will use the field specified in get_latest_by by default.

Like get(), latest() raises DoesNotExist if an object doesn't exist with the given parameters.

Note latest() exists purely for convenience and readability.

And the model docs on get_latest_by:

get_latest_by

Options.get_latest_by

The name of a DateField or DateTimeField in the model. This specifies the default field to use in your model Manager's latest method.

Example:

get_latest_by = "order_date"

See the docs for latest() for more.

Edit: Wade has a good answer on Q() operator.

于 2009-08-10T18:04:21.637 に答える
45

これはうまくいきます!

Model.objects.latest('field')-フィールドはidにすることができます。それが最新のIDになります

于 2009-12-11T09:28:20.240 に答える
18

最大の主キーについては、次のことを試してください。

List.objects.order_by('-pk')[0]

pk主キーとして定義されているフィールドの実際の名前に関係なく、使用が機能することに注意してください。

于 2009-08-10T19:58:19.347 に答える
3

アイテムの数を取得するには、クエリ セットで count() メソッドを使用できます。

list = List.objects.all()
list.count()

フィルタリングする引数は、一緒に「AND」されます。OR フィルターを実行する必要がある場合は、Q オブジェクトを調べてください。 http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

于 2009-08-10T17:46:11.190 に答える