简体   繁体   English

如何在 Django 中检查两个模型是否相等?

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

models.py:模型.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?如何检查 office_list 名称是否等于 tg_list 名称? I want to check if any of the office_list.name == any of the tg_list.name我想检查是否有任何 office_list.name == 任何 tg_list.name

if you want如果你想

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

you can do simple query with exists :您可以使用exists进行简单查询:

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

From the Django doc :来自Django 文档

To compare two model instances, just use the standard Python comparison operator, the double equals sign: == .比较两个模型实例,只需使用标准 Python 比较运算符,即双等号: == Behind the scenes, that compares the primary key values of two models.在幕后,比较两个模型的主键值。

or :

Youu can do with __eq__ in python too:你也可以在 python 中使用__eq__

See python docs too.也请参阅python 文档

The accepted answer requires an DB call, and specifically checks 1 field.接受的答案需要数据库调用,并专门检查 1 字段。 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.在更现实的情况下,您将检查某些字段子集是否相等 - 可能会忽略 PK、创建时间戳等。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM