Search code examples
pythondjangologic

Django Field comprising of other fields


enter image description here

class Car(models.Model):
    stockid = models.AutoField(primary_key=True)

    galleryIndex = models.IntegerField()
    title = make + model + year

    make = models.CharField(max_length=50)
    model = models.CharField(max_length=200)
    year = models.IntegerField()
    price = models.IntegerField()

    location = models.CharField(max_length=50)
    mileage = models.IntegerField()
    transmission = models.BooleanField(default=False)

    engine = models.CharField(max_length=200)
    registration = models.CharField(max_length=200)
    body = models.CharField(max_length=200)
    color = models.CharField(max_length=200)

    sellerComments = models.CharField(max_length=300)

I want to achieve the title field,

actually i need this to find the car model!

like in query i will send a string for example: "MAKE MODEL" user can either send a make a make or a model, it cant be figured out bcs theres a single search box! anyways if i have a "title field" i can use it to query data

in this way " where title contains query string!" and thats the only logic i can think of!

any help would be great!

Query Make and Model according to a String!


Solution

  • What you want may be simply achieved by overriding save method on current class, so you define title as normal character field and until object is saved generate its value from other fields that you want.

    So in your example your save method may look like this:

    def save(self, *args, **kwargs):
        # generate title field from other fields on each model creation/edit
        self.title = f"{self.make} {self.model} {self.year}"
         
        # run default Django implementation for save method 
        super().save(*args, **kwargs)
    

    and your title field on model may look like this:

    title = models.CharField(max_length=256)