简体   繁体   中英

Passing a variable from views.py to models.py django

I am still very new to programming.

My issue is this I have 2 models, one for Sale and one for Agent.

now to render each Agent and the sales they made(with different attributes) uniquely I needed to write model methods under my sale model to allow to me to call them in the template.

Now my issue is this, I want to be able to render that exact thing but by what dates the user chooses, I have tried manually doing this through my project files and it works, but I want to know is it possible to have those values moved from user into my method? What I mean is there is a basic form in the nav bar that allows the person to choose a from and to date, but those values I am not sure how to pass them into my models.py under the method where I need this date range applied.

I will show an example.

#this is my view that grabs relevant dates
def asearch_stats(request):
    if request.method == 'POST':
        from_date = request.POST['from']
        to_date = request.POST['to']
        return render(request,"Sales/salesfilter.html",{"flookup":flookup})


# this is my model with the methods I'm referring to below:
class SalesAgent(models.Model):
    user = models.OneToOneField(User,on_delete=models.SET_NULL,null=True,related_name="sauser")
    SA_name = models.CharField(max_length=40)
    role = models.CharField(choices=Roles,default="default",max_length=13)
    def __str__(self):
        return self.user.username

    #FILTERED SEARCH
# I need those dates on the below ones to be the variables like something like this
    def get_dates(request):
        if request.method == 'POST':
            from_date = request.POST['from']
            to_date = request.POST['to']

    def sfget_totals(self):
        return self.agent_sale.filter(Date_created__gte=(from_date),Date_created__lte=(to_date))
    def sfget_confirmed(self):
        return self.agent_sale.filter(State="Confirmed",Date_created__gte=('2022-03-01'),Date_created__lte=('2022-03-02'))
    def sfget_debi(self):
        return self.agent_sale.filter(AcknowledgeQA=True,State="Confirmed",Debi_status="Accepted",Date_created__gte=('2022-03-01'),Date_created__lte=('2022-03-02'))
    def sfget_requested(self):
        return self.agent_sale.filter(Debi_status="Requested",Date_created__gte=('2022-03-01'),Date_created__lte=('2022-03-02'))
    def sfget_cancelled(self):
        return self.agent_sale.filter(State="Cancelled",Date_created__gte=('2022-03-01'),Date_created__lte=('2022-03-02'))
    def sfget_pending(self):
        return self.agent_sale.filter(State="Pending",Date_created__gte=('2022-03-01'),Date_created__lte=('2022-03-02'))



You can't. Models encapsulate and abstract database tables. Views exist at a higher level. A model cannot refer to "its" view, because a model instance can exist without any view at all. For example, when you are working in a management command, or the shell, or a Celery task.

Maybe these methods should be (Class-based) view methods, not object methods. There's no reason you cannot pass the view to the template. The Class-based views do his by default (as context variable view )

If you wish to have model instance methods that depend on from and to dates from the nav bar, you have to pass them in.

class SalesAgent(models.Model):
...

    def method(self, from_date, to_date)

You will invoke this method from your view(s), where it will be something like

   agent = SalesAgent.objects.get( ...)
   agent.method( from_date = request.POST['from'], to_date = request.POST['to']  )

It's possible (if a little "hacky" to "stamp" an object in your view so that a whole bunch of methods don't need to be explicitly told about these dates

   agent = SalesAgent.objects.get( ...)
   agent._from_date = request.POST['from']
   agent._to_date   = request.POST['to']

Now, you have to make sure that your code which depends on these fields fails gracefully (or applies defaults): Things like

def method( self):
    from_date = getattr( self, '_from_date', datetime.date( 1900,1,1) )
    to_date = getattr( self, '_to_date', datetime.date.today() )

which default (sensibly? ) if the stamps have not been applied. Alternatively,

if not hasattr( self, '_to_date'):
    raise AttributeError (
        'SalesAgent object method "method" has been called in an invalid context: instance attribute "_to_date" is not yet set' )

I suppose it's always possible to attach the entire request or even the entire view to an object instance, if you really want to. Same caveat about defaulting or failing understandably.

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