将查询转换为django中的列表

时间:2017-09-06 17:03:29

标签: python django

我在views.py

中有这段代码
def prod_aff(request):
    queryset =Produit.objects.all()
    ca = sortiestk.objects.all().select_related('ref').select_related('codecateg').values_list('ref__codecateg',flat=True).distinct()
    ca1 = list(ca)
    print ca1
    for val in ca1:
        pp = sortiestk.objects.select_related('ref').select_related('codecateg').filter(ref__codecateg=val).aggregate(Sum('qtesrt'))
        print pp
    return render(request, 'produit/produit.html',{'nomc':getnomcat,'produit':queryset})

显示:

{'qtesrt__sum': 8},
{'qtesrt__sum': 40},
{'qtesrt__sum': 10}

我想只将int值放在列表中。我试过了list(pp),但它只展示了[qtesrt__sum , qtesrt__sum ,qtesrt__sum]

3 个答案:

答案 0 :(得分:1)

试试这个:

list(pp.values())

这将为您提供pp的值列表,这些值正是您想要的整数。如果你运行

list(pp)

你得到了密钥列表,因为这个陈述等同于

list(pp.keys())

如果要将pp的键和值都放入列表中,可以执行

list(pp) + list(pp.values())

答案 1 :(得分:1)

如果您需要对分组中的查询结果进行展平,则可以使用annotate代替aggregate

pp = sortiestk.objects.select_related('ref').select_related('codecateg').filter(ref__codecateg=val).annotate(qtesrt_total=Sum('qtesrt')).values_list('qtesrt_total', flat=True)

输出将是:

[8,40,10]

答案 2 :(得分:0)

根据文档QuerySet,您只需 <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/back" tools:context="com.food.sheenishere.stark.MainActivity"> <com.google.android.gms.common.SignInButton android:id="@+id/googlebtn" android:layout_width="286dp" android:layout_height="49dp" android:layout_marginEnd="24dp" android:layout_marginLeft="24dp" android:layout_marginRight="24dp" android:layout_marginStart="24dp" android:layout_marginTop="270dp" app:layout_constraintHorizontal_bias="0.502" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"> </com.google.android.gms.common.SignInButton> </android.support.constraint.ConstraintLayout> package com.food.sheenishere.stark; import android.app.ActionBar; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Toast; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; public class MainActivity extends AppCompatActivity { private SignInButton mGoogleBtn; private static final int RC_SIGN_IN=1; private GoogleApiClient mGoogleApiClient; private FirebaseAuth mAuth; private static final String TAG="MAINACTIVITY"; private FirebaseAuth.AuthStateListener mAuthListener; // A progress dialog to display when the user is connecting in // case there is a delay in any of the dialogs being ready. private ProgressDialog mConnectionProgressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAuth=FirebaseAuth.getInstance(); mAuthListener=new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (firebaseAuth.getCurrentUser() !=null){ startActivity(new Intent(MainActivity.this,profilemain.class)); } } }; mGoogleBtn=(SignInButton) findViewById(R.id.googlebtn); // Configure the ProgressDialog that will be shown if there is a // delay in presenting the user with the next sign in step. mConnectionProgressDialog = new ProgressDialog(this,R.style.MyAlertDialogStyle); mConnectionProgressDialog.setMessage("Signing in..."); // Configure Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleApiClient=new GoogleApiClient.Builder(getApplicationContext()) .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { Toast.makeText(MainActivity.this,"you got an error", Toast.LENGTH_SHORT).show(); } }) .addApi(Auth.GOOGLE_SIGN_IN_API,gso) .build(); mGoogleBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { signIn(); } }); } @Override protected void onStart() { super.onStart(); mAuth.addAuthStateListener(mAuthListener); } private void signIn() { Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); mConnectionProgressDialog.setMessage("Signing in..."); mConnectionProgressDialog.show(); if (result.isSuccess()) { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = result.getSignInAccount(); firebaseAuthWithGoogle(account); } else { // Google Sign In failed, update UI appropriately Toast.makeText(MainActivity.this, "Something went wrong.", Toast.LENGTH_SHORT).show(); mConnectionProgressDialog.dismiss(); // ... } } } private void firebaseAuthWithGoogle(GoogleSignInAccount account) { AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); mConnectionProgressDialog.dismiss(); // updateUI(user); } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithCredential:failure", task.getException()); Toast.makeText(MainActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show(); // updateUI(null); } // ... } }); } } 用户即可将查询转换为列表。