Django
django many to many를 id로 정렬하는 방법
대구 올빼미
2021. 3. 17. 09:26
이런 모델이 있다.
class section_products(models.Model):
products_list = models.ManyToManyField(Product, verbose_name="관련 상품")
이렇게 되면 products를 생성할 때
section_products_prdocuts_list라는 모델이 하나 더 생성된다.
그래서 하나의 해당 객체를 가지고 와서 관련된 products_list를 뽑아와서 order하고 싶을 때,
section_products = SectionProducts.objects.get(id=10)
section_products.products_list.all().order_by('-id')
=> 이렇게 하면 연결된 Product의 id로 정렬되어서 나온다.
하지만 내가 원하는 것은 새로 생성된 section_products_prdocuts_list의
id로 정렬하는 것!
많은 구글링을 통해 해결하였다.
section_products.products_list.all().order_by('section_products_products_list.id') 로 해결
관련 글 : [python - How can I sort by the id of a ManyToManyField in Django? - Stack Overflow](https://stackoverflow.com/questions/1904978/how-can-i-sort-by-the-id-of-a-manytomanyfield-in-django)