What's new

Django ORM?

0R1-qt

Honorary Poster
Established
Joined
Nov 7, 2020
Posts
290
Reaction
55
Points
152
Hello Magandang gabi patulong po sa mga malulupet jan sa Django.
bali for example may tatlo akong Car model.
Sorted ang mga yan gamit yung meta classes tapos ordering gamit alam nyo nayan.
Car A --> Car B --> Car C

Ngayun pano ako makapag query tapos maipagpalit yung position nila basin ganito nayung ordering nya after swapping.
Car C --> Car B --> Car A

Swapping lang to pero diko alam pano iimplement sa django. bali ito yung model ko.

class CarColor(models.Model):
colors = models.CharField(max_length=50)
def str(self) -> str:
return self.colors

class Car(models.Model):
car_name = models.CharField(max_length=50)
car_model = models.CharField(max_length=200)
car_description = models.TextField(max_length=200)
car_color = models.ForeignKey(CarColor, on_delete=models.CASCADE)
car_image = models.ImageField(null=True, blank=True, upload_to='media', default='imageholder.png')
date_manufactured = models.DateTimeField(auto_now_add=True)

def get_absolute_url(self):
""" After creating or updating a Car, this function will be triggered and redirection using reverse"""
return reverse("car_detail", kwargs={"pk": self.pk})

class Meta:
ordering = ['date_manufactured']

def str(self):
return f'{self.car_name}'
 
Hello! To swap the position of two Cars, you can update their date_manufactured values accordingly. Here's an example of how you can swap the positions of Car A and Car C:

1. Retrieve the Car objects you want to swap:
Code:
car_a = Car.objects.get(car_name='Car A')
car_c = Car.objects.get(car_name='Car C')

2. Swap their date_manufactured values:
Code:
car_a.date_manufactured, car_c.date_manufactured = car_c.date_manufactured, car_a.date_manufactured
car_a.save()
car_c.save()
This code first swaps the date_manufactured values of the car_a and car_c objects, and then saves them to the database.

After the code above has been run, the position of Car A and Car C in the ordering of Car objects would have been swapped. You can verify this by executing the following code:
Code:
cars = Car.objects.all()
print([car.car_name for car in cars])
This should give you the output ['Car C', 'Car B', 'Car A'], which shows that the positions of Car A and Car C have indeed been swapped.

Please note that if the date_manufactured values of the Car objects you're swapping are the same, the ordering of the objects in the queryset will not change. In this case, you may want to consider adding another field to your model to use for sorting.
 
Back
Top