简体   繁体   中英

How to make queries directly on the models.py file in django, to fill the fileds with the results?

Hi I want to know If I am able to work directly with queries inside the "models.py" file to make results the default values of some fields. For example:

class NewModel(models.Model): Seats = models.IntegerField(default=<some_result_of_a_query>)...

Thanks: :)

For a project I manage to do it with:

in model.py:

class SQLQueryCache(models.Model):
    SQLquery=models.TextField(blank=True,null=True,unique=True)
    data_refresh_period_in_minuts=models.IntegerField(blank=True,null=True)



class SQLQueryCacheForm (ModelForm):
    def __init__(self, SQLPK,*args, **kwargs):
        super(SQLQueryCacheForm, self).__init__(*args, **kwargs)
        dict_value=SQLQueryCache.objects.filter(pk=SQLPK).values('SQLquery','data_refresh_period_in_minuts')
        for value in dict_value:
            self.fields['SQLquery']=forms.CharField(required=False,initial=value['SQLquery'],widget=forms.Textarea(attrs={'rows': 10, 'cols': 90,'style': 'font-size: 10px'}))
            self.fields['data_refresh_period_in_minuts']=forms.CharField(required=False,initial=value['data_refresh_period_in_minuts'],widget=forms.TextInput(attrs={'type': 'number','style':'width:150px; height:30px'}))

    class Meta:
        model = SQLQueryCache
        fields = ['SQLquery','data_refresh_period_in_minuts']

in view.py:

from .models import SQLQueryCache,SQLQueryCacheForm

def NewDashboardBuilder (request):
    formset['SQL']= SQLQueryCacheForm(SQLPK=componentInstance.SQLquery_FK.pk)
    return render(request, "formTest/Formset.html", {'formset': formset})

in formset.html:

  <!-- SQL part -->
  {% if formset.SQL %}
    <div class="row even">
      <div class='col-'style="padding:5px">
        {{ formset.SQL.as_p }}
      </div>
    </div>

You can define a method on the model that returns the value you want and point the default of your field to that method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM