abctest
abctest

Reputation: 163

How can I check if two models equal each other in Django?

models.py:

class office_list(models.Model):
    name = models.CharField(max_length= 100)
    num_of_pax = models.IntegerField()

class tg_list(models.Model):
    name = models.CharField(max_length= 100)
    num_of_pax = models.IntegerField()

How can I check that the office_list name equals to the tg_list name? I want to check if any of the office_list.name == any of the tg_list.name

Upvotes: 1

Views: 1653

Answers (3)

Dougyfresh
Dougyfresh

Reputation: 616

The accepted answer requires an DB call, and specifically checks 1 field. In a more realistic scenario, you would be checking some subset of fields to be equal - likely ignoring PK's, creation timestamps, amongst other things.

A more robust solution would be something like:

class MyModel(Model):
    some_field_that_is_irrelevant_to_equivalence = models.CharField()
    some_char_field = models.CharField()
    some_integer_field = models.IntegerField()

    _equivalent_if_fields_equal = (
        'some_char_field',
        'some_integer_field',
    )

    def is_equivalent(self, other: 'MyModel') -> bool:
        """Returns True if the provided `other` instance of MyModel
        is effectively equivalent to self.

        Keyword Arguments:
        -- other: The other MyModel to compare this self to
        """
        for field in self._equivalent_if_fields_equal:
            try:
                if getattr(self, field) != getattr(other, field):
                    return False
            except AttributeError:
                raise AttributeError(f"All fields should be present on both instances. `{field}` is missing.")
        return True

Upvotes: 0

user8060120
user8060120

Reputation:

if you want

any of the office_list.name == any of the tg_list.name

you can do simple query with exists:

names = tg_list.objects.values_list('name', flat=True)
office_list.objects.filter(name__in=names).exists()

Upvotes: 2

user9818446
user9818446

Reputation:

From the Django doc :

To compare two model instances, just use the standard Python comparison operator, the double equals sign: ==. Behind the scenes, that compares the primary key values of two models.

or :

Youu can do with __eq__ in python too:

See python docs too.

Upvotes: 1

Related Questions