3

I have two classes: A and B. Each A has an ordered ranking of Bs, and each B has an ordered ranking of As.

My models.py:

class A(models.Model):
    name = models.CharField(max_length=200)
    ...

class B(models.Model):
    name = models.CharField(max_length=200)
    ...

class Ranking(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    rankofa = models.IntegerField()
    rankofb = models.IntegerField()

Examples of what I need to do:

  • Find the number of As that a B has ranked.
  • Iterate in order through all Bs ranked by a particular A and evaluate some property of B.
  • Go to an A's lowest-ranked B, and find the ranking given by that B to that A.

I'd like to set up the rankings as an array/list of objects (or some way that does not keep making expensive database calls), but not sure how to do this as a Django models/database solution.

Any and all thoughts appreciated.

1 Answer 1

2

What you need is intermediary M2M relation

class Seller(models.Model):
    name = models.CharField(max_length=200)

class Customer(models.Model):
    name = models.CharField(max_length=200)
    feedbacks = models.ManyToManyField(Seller, through='Feedback', related_name='feedbacks')

class Feedback(models.Model):
    seller = models.ForeignKey(Seller)
    customer = models.ForeignKey(Customer)
    seller_feedback = models.IntegerField()
    customer_feedback = models.IntegerField()

Find the number of sellers customer has ranked:

customer.feedbacks.all().count()

Iterate in order through all customers ranked by a particular seller and evaluate some customer property.

for customer in seller.feedbacks.all():
    do_something(customer)

Go to an sellers's lowest-ranked customer, and find the ranking given by that customer to that a seller.

def lowes_feedback_response(seller):
    try:
        return models.Feedback.filter(seller=seller).order_by('-seller_feedback')[0].customer_feedback
    except models.Feedback.DoesNotExist:
        return None

I didn't evaluate the code but you get the basic idea

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.