简体   繁体   中英

How to fetch data from database django

I have created a CustomerRegistration model and I want that if the phone no exists in the database, then all the details of the customer will display automatically in form.

here is my models.py

class CustomerRegistration(models.Model):
    name = models.CharField(max_length=254, null=False)
    email = models.EmailField(max_length=254, null=False)
    date_of_birth = models.DateTimeField(null=False)
    country_id = models.ForeignKey('accounts.Country', null=False, on_delete=models.CASCADE, related_name='Country')
    state_id = models.ForeignKey('accounts.State', null=False, on_delete=models.CASCADE, related_name='State')
    cities_id = models.ForeignKey('accounts.City', null=False, on_delete=models.CASCADE, related_name='city')
    address = models.CharField(max_length=254, null=False)
    refernce_by_person_name = models.CharField(max_length=254, null=False)
    refernce_by_person_contact_no = models.IntegerField(null=True)
    phone_no = models.IntegerField(null=False, primary_key=True)
    alternate_no = models.IntegerField(null=False)
    hobbies = models.CharField(max_length=254)


    def __str__(self):
        return self.name

Have a look at making queries in the django documentation. You will want to make a query to your databse, and if you get any results, populate your form with the correct info.

This would look something like:

from .models import CustomerRegistration

results = CustomerRegistration.objects.all().filter(phone=given_number)

then, if there are any results, you can use it to populate your form!

You can query like this to understand that user has phone number or not or something like that:

CustomerRegistration.objects.filter(phone_no__isnull=False)

isnull specifies that a field is none or not

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