Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django many-to-many compare

Is any way to compare two ManyToMany relationship from a different models?

I have a model Days in common and with this other two models:

  • Ticket (The Ticket has a m2m relation with Days)
  • Check (The check has a m2m relation with Days)

I can do it with two for what don't look really pretty or readable.

like image 787
JMira Avatar asked Dec 13 '25 14:12

JMira


1 Answers

If i'm reading your question correctly, you can achieve what you are asking for by defining related names in the m2m declarations in the Ticket and Check models and then comparing querysets

example:

class Day(models.Model):
    day = models.DateField()

class Ticket(models.Model):
    ticket_name = models.CharField()
    days = models.ManyToMany(Day, related_name="tickets")

class Check(models.Model):
    check_name = models.CharField()
    days = models.ManyToMany(Day, related_name="checks")

now to find all the tickets and checks for a specified day to compare them you can do:

date = datetime.date(day=1, month=1, year=2000)
day = Day.objects.select_related().get(day=date)

ts = day.tickets
cs = day.checks

if you want all the checks on the days that are related to a Ticket with ticket_name = ticket:

checks_for_ticket = Check.objects.filter(days__tickets__ticket_name="tickets")

if you want all the tickets on the days that are related to a Check with check_name = check:

tickets_for_check = Ticket.objects.filter(days__checks__check_name="check")
like image 166
dting Avatar answered Dec 16 '25 11:12

dting



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!